2

我的注释如下所示:

@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在每种情况下我做错了什么?

4

1 回答 1

7

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

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsCrossSellingRevelant
{
  boolean value() default true;
}
于 2013-08-29T12:57:13.670 回答