本文將討論用Java建立註解的方法。還有如何將註解應用於其餘聲明。最後,討論一下如何在運行時使用Reflection得到註解信息。程序員
註解是J2SE 5引入的一項新功能,容許程序員將稱爲元數據的其餘信息嵌入Java源文件中。註解不會改變程序的執行,可是在開發和部署期間,各類工具均可以使用使用註解嵌入的信息。ide
建立註解與建立接口類似。只不過註解聲明前面有一個@
符號。註解聲明自己使用註解進行@Retention
註解。該@Retention
註解用於指定保留策略,能夠是SOURCE
,CLASS
或RUNTIME
。工具
RetentionPolicy.SOURCE
僅在源文件中保留註解,並在編譯期間將其丟棄。RetentionPolicy.CLASS
將註解存儲在.class文件中,但在運行時不可用。RetentionPolicy.RUNTIME
將註解存儲在.class文件中,並使其在運行時可用。// Specifying runtime retention policy @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { String author(); // Annotation member String date(); // Annotation member }
註解會隱式擴展Annotation
接口。註解的主體由不帶主體的方法聲明組成。這些方法像字段同樣工做。code
在上面的例子中,我已經建立了兩個部件,author
並date
以表示關於建立者的信息,而且類和方法的寫入日期。orm
建立註解後,能夠將其應用於類,方法,字段,參數,枚舉等。在對聲明應用註解時,必須爲其成員提供以下值:對象
// Applying annotation to the class @MyAnnotation(author="Azim",date="22/10/2011,23/10/2011") public class Test { // Applying annotation to the method @MyAnnotation(author="Azim",date="22/10/2011") public static void testMethod() { System.out.println("Welcome to Java"); System.out.println("This is an example of Annotations"); } public static void main(String args[]) { testMethod(); showAnnotations(); }
能夠在運行時使用Reflection來查詢註解,以下所示:接口
public static void showAnnotations() // Function to show annotation information { Test test=new Test(); // Instantiating Test class try { Class c=test.getClass(); // Getting Class reference Method m=c.getMethod("testMethod"); // Getting Method reference // Getting Class annotation MyAnnotation annotation1= (MyAnnotation)c.getAnnotation(MyAnnotation.class); // Getting Method annotation MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class); // Displaying annotation information System.out.println("Author of the class: "+annotation1.author()); // Displaying annotation information System.out.println("Date of Writing the class: "+annotation1.date()); // Displaying annotation information System.out.println("Author of the method: "+annotation2.author()); // Displaying annotation information System.out.println("Date of Writing the method: "+annotation2.date()); } catch(NoSuchMethodException ex) { System.out.println("Invalid Method..."+ex.getMessage()); } }
在上面的代碼中,我查詢了應用於類Test
以及method的註解testMethod()
。ci
要獲取該類的註解信息,請使用如下語句:開發
MyAnnotation annotation1=(MyAnnotation)c.getAnnotation(MyAnnotation.class);
要獲取該方法的註解信息,請使用如下語句:部署
MyAnnotation annotation2=m.getAnnotation(MyAnnotation.class);
經過使用註解對象來打印註解信息。
問題:註解聲明後,在運行期如何查詢它的信息?
答:使用Reflection來查詢註解