本文介紹了通過使用反射獲取帶有注釋的字段列表的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我創建我的注釋
public @interface MyAnnotation {
}
我把它放在我的測試對象的字段上
I put it on fields in my test object
public class TestObject {
@MyAnnotation
final private Outlook outlook;
@MyAnnotation
final private Temperature temperature;
...
}
現在我想用 MyAnnotation
獲取所有字段的列表.
Now I want to get list of all fields with MyAnnotation
.
for(Field field : TestObject.class.getDeclaredFields())
{
if (field.isAnnotationPresent(MyAnnotation.class))
{
//do action
}
}
但似乎我的塊執行操作從未執行,并且字段沒有注釋,因為以下代碼返回 0.
But seems like my block do action is never executed, and fields has no annotation as the following code returns 0.
TestObject.class.getDeclaredField("outlook").getAnnotations().length;
有人可以幫助我并告訴我我做錯了什么嗎?
Is anyone can help me and tell me what i'm doing wrong?
推薦答案
您需要將注解標記為在運行時可用.將以下內容添加到您的注釋代碼中.
You need to mark the annotation as being available at runtime. Add the following to your annotation code.
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
這篇關于通過使用反射獲取帶有注釋的字段列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!