1. 程式人生 > >Java反射機制實現全部註解獲取

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才能在程式執行時被反射機制取得。