自定义注解

问题

如何通过注解值得到对应成员变量?

学习注解

自定义注解

@Inherited
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Index {
    String name() default "";
}

定义User类

import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
public class User {
    @Index(name = "userNo")
    private int userId;
    @Index(name = "Name")
    private String userName;
}

其中lombok的依赖配置为

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
</dependency>  

测试注解

public class UserTest {
    private void test1() {
        Class<User> clazz = User.class;
        Field[] fields = clazz.getDeclaredFields();
        List<Field> result = new ArrayList<>();
        for (Field field : fields){
            if(field.getAnnotation(Index.class)!=null) {
                result.add(field);
            }
        }

        for(Field list:result){
            System.out.println("被注解的字段为:" + list.getName());
        }
    }

    private void test2() {
        Class<User> clazz = User.class;
        Field[] fields = clazz.getDeclaredFields();
        List<String> result = new ArrayList<>();
        for (Field field : fields){
            if(field.getAnnotation(Index.class)!=null) {
                result.add(field.getAnnotation(Index.class).name());
            }
        }

        for(String list:result){
            System.out.println("注解的字段为:" + list);
        }
    }

    public static void main(String[] args) {
        UserTest userTest = new UserTest();
        userTest.test1();
        userTest.test2();
    }
}

结果

被注解的字段为:userId
被注解的字段为:userName
注解的字段为:userNo
注解的字段为:Name

解决

private void test3() {
        Map<String, String> annotation2Field = new HashMap<>();
        Class<User> clazz = User.class;
        
        
        
        Field[] fields = clazz.getDeclaredFields();
        List<String> result = new ArrayList<>();
        for (Field field : fields){
            if(field.getAnnotation(Index.class)!=null) {
                result.add(field.getAnnotation(Index.class).name());
                annotation2Field.put(field.getAnnotation(Index.class).name(), field.getName());
            }
        }
        annotation2Field.forEach((k, v)-> System.out.println(k + ":" + v));

    }