我的注释看起来像这样:
@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);
但是阵列annotations
和annotations2
是空的,isRelevant
在每种情况下我做错了什么?
答案 0 :(得分:5)
您需要在注释上添加@Retention注释,将@Retention.value设置为RetentionPolicy.RUNTIME,如下所示:
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface IsCrossSellingRevelant
{
boolean value() default true;
}