2013-08-29 37 views
2

我的註釋是這樣的:現場#getAnnotation()不能與自己的註釋工作

@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在任何情況下我做錯了什麼?

回答

5

您需要添加您的註解@Retention註釋,設置@Retention.valueRetentionPolicy.RUNTIME這樣的:

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