问题
如何通过注解值得到对应成员变量?
学习注解
自定义注解
@Inherited@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface Index { String name() default "";}
定义User类
import lombok.Getter;import lombok.Setter;@Setter@Getterpublic class User { @Index(name = "userNo") private int userId; @Index(name = "Name") private String userName;}
其中lombok的依赖配置为
org.projectlombok lombok 1.18.2
测试注解
public class UserTest { private void test1() { Classclazz = User.class; Field[] fields = clazz.getDeclaredFields(); List 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 clazz = User.class; Field[] fields = clazz.getDeclaredFields(); List 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() { Mapannotation2Field = new HashMap<>(); Class clazz = User.class; Field[] fields = clazz.getDeclaredFields(); List 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)); }