我在java中有以下类:
public class Classic {
@Annotate1(location="foo", name="bar")
public final Comp1 comp1 = new Comp1();
@Annotate2(member="blessed")
public final Comp2 comp2 = new Comp2();
}
现在,在一个单独的课程中,我可以访问Classic
,Comp1
和Comp2
的对象。在同一个地方,我不知道Classic.
中字段的名称
如何获取comp1
和comp2
对象的注释?
答案 0 :(得分:2)
这是一个让你入门的例子:
public class Classic {
@Annotate1(location = "foo", name = "bar")
public final Comp1 comp1 = new Comp1();
@Annotate2(member = "blessed")
public final Comp2 comp2 = new Comp2();
public static void main(String[] args) {
Class clazz = Classic.class;
for(Field field: clazz.getDeclaredFields()){
if(field.isAnnotationPresent(Annotate1.class)){
Annotate1 annotate1 = field.getAnnotation(Annotate1.class);
System.out.println(annotate1.name());
}else if(field.isAnnotationPresent(Annotate2.class)){
Annotate2 annotate2 = field.getAnnotation(Annotate2.class);
System.out.println(annotate2.member());
}
}
}
}
如果您正在制作自己的注释,请确保将它们设置为在运行时保留:
@Retention(RetentionPolicy.RUNTIME) //Important
public @interface Annotate1 {
String name();
String location();
}