获取类中特定对象的注释

时间:2013-12-16 20:32:05

标签: java reflection annotations

我在java中有以下类:

public class Classic {
    @Annotate1(location="foo", name="bar")
    public final Comp1 comp1 = new Comp1();

    @Annotate2(member="blessed")
    public final Comp2 comp2 = new Comp2();
}

现在,在一个单独的课程中,我可以访问ClassicComp1Comp2的对象。在同一个地方,我不知道Classic.中字段的名称 如何获取comp1comp2对象的注释?

1 个答案:

答案 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();

}