Annotation是JDK1.5的新特性,它能夠讓程序開發更加的快速方便,特別是體如今取代xml配置文件方面。
JDK1.5以後自帶了三個已經實現的Annotation,分別是@Override, @Deprecated, @SuppressWarnings.
對於自定義Annotation,編譯器幫咱們實現了不少內部細節,好比實現了Annotation接口(固然還不止這個),咱們不用也不能再去實現
Annotation接口或者其餘任何接口了。這是JDK的規範所規定的。
主要用到的API包括:
下面直接看例子:
package com.ec.test; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * 自定義Annotation * Retention是標註這個Annotation將被保持多久。其所保持的時間保存在RetentionPolicy中 * 默認狀況下的保持時間是RetentionPolicy.CLASS,即到class文件中,可是不被虛擬機所讀取 * RetentionPolicy.RUNTIME 是保持到class文件中 ,而且能夠被虛擬機讀取 * RetentionPolicy.SOURCE 是隻在編譯期,事後即被廢棄 * @author nange * @version 1.0 */ @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String hello() default "nange"; //定義了一個hello字段,默認值爲nange String world(); //定義了一個world字段,沒有默認值 }
--------------------------------------------------------------------------------------------------------
package com.ec.test; /** * 此類中有一個output方法上面使用了自定義的MyAnnotation * @author nange * @version 1.0 */ public class MyTest { //對MyAnnotation中的屬性賦值,將覆蓋默認的值 @MyAnnotation(hello="beijing", world="shanghai") public void output(int i, int j) { System.out.println("output something..." + i + j); } }
--------------------------------------------------------------------------------------------------------
package com.ec.test; import java.lang.annotation.Annotation; import java.lang.reflect.Method; /** * 定義MyReflection類,利用反射機制獲得在MyTest類中的output * 方法上面使用的MyAnnotation * @author nange * @version 1.0 */ public class MyReflection { public static void main(String[] args) throws Exception { MyTest myTest = new MyTest();//獲得myTest對象,用於後面的invoke調用方法測試 Class<MyTest> c = MyTest.class;//獲得MyTest的類對象 //獲得output方法對象,getMethod方法的對一個參數是方法的名稱,第二個參數是方法參數類型列表 //保存在一個Class對象數組中 Method method = c.getMethod("output", new Class[]{int.class, int.class}); if (method.isAnnotationPresent(MyAnnotation.class)) {//判斷在此方法上是否有MyAnnotation註解 //利用反射執行這個方法,第一個參數是這個方法所在的對象,第二個參數是這個方法的執行的參數列表 //保存在一個Object對象數組中 method.invoke(myTest, new Object[]{1,2}); MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class); //一樣利用反射獲得MyAnnotation對象 String hello = myAnnotation.hello();//獲得hello的值 String world = myAnnotation.world();//獲得world的值 System.out.println(hello);//打印 System.out.println(world); } Annotation[] annotations = method.getAnnotations();//獲得在此方法上定義的所用註解對象 for (Annotation annotation : annotations) { //循環遍歷註解對象,一樣利用反射機制,打印出這些註解的完整名稱(包括包路徑) System.out.println(annotation.annotationType().getName()); } } } |