今天就跟大家聊聊有關Java中怎么利用反射機制獲取全部注解,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
一 代碼
class Info{ //給mytoString方法加了2個內建Annotation @Deprecated @SuppressWarnings(value = "This is a waring!") public String mytoString(){ return "hello world"; }}class GetAnnotations{ public static void main(String[] args) throws Exception { Class<?> cls=Class.forName("Info"); Method toStringMethod=cls.getMethod("mytoString"); //取得全部的注解 Annotation ans[]=toStringMethod.getAnnotations(); for(int i=0;i<ans.length;i++) { //獲得mytoString方法上的所有Annotation。 System.out.println(ans[i]); } }}
二 運行結果
@java.lang.Deprecated()
三 說明
2個內建的Annotation中只有@Deprecated是RUNTIME類型,所以只輸出了Deprecated。
只有定義了@Retention(value=RUNTIME)的Annotation才能在程序運行時被反射機制取得。
看完上述內容,你們對Java中怎么利用反射機制獲取全部注解有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。