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

Phi*_*der 2 java reflection annotations

我的注释看起来像这样:

@Documented
@Target(ElementType.FIELD)
public @interface IsCrossSellingRevelant
{
    boolean value() default true;
}
Run Code Online (Sandbox Code Playgroud)

我的ModelClass看起来像这样

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

public class B extends A {
    private String irrelevant;
}
Run Code Online (Sandbox Code Playgroud)

现在我有一个方法应该给我在类层次结构中的注释字段

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);
Run Code Online (Sandbox Code Playgroud)

但是,数组annotationsannotations2是空的,isRelevant在任何情况下我到底做错了什么?

Nic*_*olt 5

您需要添加@Retention标注上你的注释,设置@ Retention.valueRetentionPolicy.RUNTIME是这样的:

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