2013-05-16 71 views
38

創建我的註釋獲取與註釋,字段列表通過使用反射

public @interface MyAnnotation { 
} 

我把它放在場在我的測試對象

public class TestObject { 

    @MyAnnotation 
    final private Outlook outlook; 
    @MyAnnotation 
    final private Temperature temperature; 
    ... 
} 

現在,我想所有的字段列表MyAnnotation

for(Field field : TestObject.class.getDeclaredFields()) 
{ 
    if (field.isAnnotationPresent(MyAnnotation.class)) 
     { 
       //do action 
     } 
} 

但好像我的塊做永遠不會執行的動作和字段沒有註釋如下面的代碼返回0

TestObject.class.getDeclaredField("outlook").getAnnotations().length; 

是任何人都可以幫助我,告訴我,我在做什麼錯誤?

+0

1)爲了更好地幫助越早,張貼[SSCCE](http://sscce.org/)。 2)請在句子開頭添加大寫字母。還要使用大寫字母I和專有名稱(如Java),以及縮寫和首字母縮略詞(如JEE或WAR)。這使人們更容易理解和幫助。 –

+0

[How to get annotations of a member variable?](http://stackoverflow.com/questions/4453159/how-to-get-annotations-of-a-member-variable) – fglez

回答

54

您需要將註釋標記爲在運行時可用。將以下內容添加到註釋代碼中。

@Retention(RetentionPolicy.RUNTIME) 
public @interface MyAnnotation { 
} 
+0

這是正確的。但是,我認爲Annotation適合運行時使用。 – wrivas

+3

@wrivas並非所有的註釋都是針對運行時的。例如'@ SuppressWarnings'是RetentionPolicy.SOURCE,因爲它只是提示編譯器不警告某些事情。 – Patrick

+0

註解僅用於源代碼(供您閱讀),編譯時或運行時 – 2016-04-01 02:11:30

6
/** 
* @return null safe set 
*/ 
public static Set<Field> findFields(Class<?> classs, Class<? extends Annotation> ann) { 
    Set<Field> set = new HashSet<>(); 
    Class<?> c = classs; 
    while (c != null) { 
     for (Field field : c.getDeclaredFields()) { 
      if (field.isAnnotationPresent(ann)) { 
       set.add(field); 
      } 
     } 
     c = c.getSuperclass(); 
    } 
    return set; 
} 
+11

Apache Commons具有此功能:FieldUtils.getFieldsListWithAnnotation(...) – DBK