Field#getAnnotation()不使用自己的注释

时间:2013-08-29 12:53:58

标签: java reflection annotations

我的注释看起来像这样:

@Documented
@Target(ElementType.FIELD)
public @interface IsCrossSellingRevelant
{
    boolean value() default true;
}

我的ModelClass看起来像这样

public abstract class A {
    @IsCrossSellingRevelant(true)
    protected String someAnnotatedFiled;
    protected String someFiled;
}

public class B extends A {
    private String irrelevant;
}

现在我有一个方法可以在类层次结构中给出带注释的字段

A object = new B();

Class<?> classIterator = object.getClass().getSuperclass();

do
{
    for (Field field : classIterator.getDeclaredFields())
    {
        field.setAccessible(true);
        IsCrossSellingRevelant isRelevant = field.getAnnotation(IsCrossSellingRevelant.class);
        Annotation[] annotations = field.getDeclaredAnnotations();
        Annotation[] annotations2 = field.getAnnotations();
    }

    classIterator = classIterator.getSuperclass();
}
while (classIterator != Object.class);

但是阵列annotationsannotations2是空的,isRelevant在每种情况下我做错了什么?

1 个答案:

答案 0 :(得分:5)

您需要在注释上添加@Retention注释,将@Retention.value设置为RetentionPolicy.RUNTIME,如下所示:

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsCrossSellingRevelant
{
  boolean value() default true;
}