深入理解Java 註解原理
*註解的用途
註解(Annotation)是JDK1.5引入的新特性,包含在java.lang.annotation包中,它是附加在代碼中的一些元資訊,將一個類的外部資訊與內部成員聯絡起來,在編 譯、運行時進行解析和使用。Java內建了一些註解(如@Override、@Deprecated等),還支援自訂註解,一些知名的架構 Struts、Hibernate、Spring都有自己實現的自訂註解,也可以自己定義註解供使用。
Annotation十分類似public、final這樣的修飾符。每個Annotation具有一個名字和成員個數>=0。每個Annotation的成員具有被稱為name=value對的名字和值(就像javabean一樣),name=value裝載了Annotation的資訊。
Annotation類(java.lang.reflect.Annotation):
Annotation類型定義了Annotation的名字、類型、成員預設值。一個Annotation類型可以說是一個特殊的java介面,它的成員變數是受限制的,而聲明Annotation類型時需要使用新文法。當我們通過java反射api訪問Annotation時,傳回值將是一個實現了該 annotation類型介面的對象,通過訪問這個對象我們能方便的訪問到其Annotation成員。後面的章節將提到在java5.0的 java.lang包裡包含的3個標準Annotation類型。其子類如下圖所示:
註解處理器類庫(java.lang.reflect.AnnotatedElement):
Java使用Annotation介面來代表程式元素前面的註解,該介面是所有Annotation類型的父介面。除此之外,Java在java.lang.reflect 包下新增了AnnotatedElement介面,該介面代表程式中可以接受註解的程式元素,該介面主要有如下幾個實作類別(如下圖所示):
Class:類定義
Constructor:構造器定義
Field:累的成員變數定義
Method:類的方法定義
Package:類的包定義
java.lang.reflect 包下主要包含一些實現反射功能的工具類,實際上,java.lang.reflect 包所有提供的反射API擴充了讀取運行時Annotation資訊的能力。當一個Annotation類型被定義為運行時的Annotation後,該註解才能是運行時可見,當class檔案被裝載時被儲存在class檔案中的Annotation才會被虛擬機器讀取。
AnnotatedElement 介面是所有程式元素(Class、Method和Constructor)的父介面,所以程式通過反射擷取了某個類的AnnotatedElement對象之後,程式就可以調用該對象的如下四個個方法來訪問Annotation資訊:
方法1:<T extends Annotation> T getAnnotation(Class<T> annotationClass): 返回改程式元素上存在的、指定類型的註解,如果該類型註解不存在,則返回null。
方法2:Annotation[] getAnnotations():返回該程式元素上存在的所有註解。
方法3:boolean is AnnotationPresent(Class<?extends Annotation> annotationClass):判斷該程式元素上是否包含指定類型的註解,存在則返回true,否則返回false.
方法4:Annotation[] getDeclaredAnnotations():返回直接存在於此元素上的所有注釋。與此介面中的其他方法不同,該方法將忽略繼承的注釋。(如果沒有注釋直接存在於此元素上,則返回長度為零的一個數組。)該方法的調用者可以隨意修改返回的數組;這不會對其他調用者返回的數組產生任何影響。
*註解類型
註解的一般格式是[修飾符] @interface [名稱]{元素}, 元素是無方法體的方法聲明,可以有預設值,如@Target的註解如下所示:
@Documented@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.ANNOTATION_TYPE)public @interface Target { ElementType[] value();}
元註解的作用就是負責註解其他註解。Java5.0定義了4個標準的meta-annotation類型,它們被用來提供對其它 annotation類型作說明。Java5.0定義的元註解:
1.@Target,
2.@Retention,
3.@Documented,
4.@Inherited
這些類型和它們所支援的類在java.lang.annotation包中可以找到。下面我們看一下每個元註解的作用和相應分參數的使用說明。
@Target:
@Target說明了Annotation所修飾的物件範圍:Annotation可被用於 packages、types(類、介面、枚舉、Annotation類型)、類型成員(方法、構造方法、成員變數、枚舉值)、方法參數和本地變數(如迴圈變數、catch參數)。在Annotation類型的聲明中使用了target可更加明晰其修飾的目標。
作用:用於描述註解的使用範圍(即:被描述的註解可以用在什麼地方)
取值(ElementType)是來源於Java.lang.annotation.ElementType中的枚舉類型元素:
1.CONSTRUCTOR:用於描述構造器
2.FIELD:用於描述域
3.LOCAL_VARIABLE:用於描述局部變數
4.METHOD:用於描述方法
5.PACKAGE:用於描述包
6.PARAMETER:用於描述參數
7.TYPE:用於描述類、介面(包括註解類型) 或enum聲明
@Retention:
@Retention定義了該Annotation被保留的時間長短:某些Annotation僅出現在原始碼中,而被編譯器丟棄;而另一些卻被編譯在class檔案中;編譯在class檔案中的Annotation可能會被虛擬機器忽略,而另一些在class被裝載時將被讀取(請注意並不影響class的執行,因為Annotation與class在使用上是被分離的)。使用這個meta-Annotation可以對 Annotation的“生命週期”限制。
作用:表示需要在什麼層級儲存該注釋資訊,用於描述註解的生命週期(即:被描述的註解在什麼範圍內有效)
取值(RetentionPoicy)來源於java.lang.annotation.RetentionPolicy的枚舉類型值:
1.SOURCE:在源檔案中有效(即源檔案保留)
2.CLASS:在class檔案中有效(即class保留)
3.RUNTIME:在運行時有效(即運行時保留)
@Documented:
@Documented用於描述其它類型的annotation應該被作為被標註的程式成員的公用API,因此可以被例如javadoc此類的工具文檔化。Documented是一個標記註解,沒有成員。
@Inherited:
@Inherited 元註解是一個標記註解,@Inherited闡述了某個被標註的類型是被繼承的。如果一個使用了@Inherited修飾的annotation類型被用於一個class,則這個annotation將被用於該class的子類。
注意:@Inherited annotation類型是被標註過的class的子類所繼承。類並不從它所實現的介面繼承annotation,方法並不從它所重載的方法繼承annotation。
當@Inherited annotation類型標註的annotation的Retention是RetentionPolicy.RUNTIME,則反射API增強了這種繼承性。如果我們使用java.lang.reflect去查詢一個@Inherited annotation類型的annotation時,反射代碼檢查將展開工作:檢查class和其父類,直到發現指定的annotation類型被發現,或者到達類繼承結構的頂層。
*註解實現執行個體 實現註解需要三個條件:註解聲明、使用註解的元素、操作註解使其起作用(註解處理器)。
定一個MyTag註解類:
import java.lang.annotation.ElementType;import java.lang.annotation.Inherited;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.METHOD,ElementType.FIELD})@Inherited@Retention(RetentionPolicy.RUNTIME)public @interface MyTag {String name() default "車";int size() default 10;}
定義一個實體Car類:
public class Car {private String name;private int size;public String getName() {return name;}public void setName(String name) {this.name = name;}public int getSize() {return size;}public void setSize(int size) {this.size = size;}public Car(){}public Car(String name, int size){this.size = size;this.name = name;}@Overridepublic String toString() {return "Car [name=" + name + ", size=" + size + "]";}}
定義一個使用註解的類AnnotationDemo類:
public class AnnotationDemo{@MyTag(name = "audi", size = 10)private Car car;public Car getCar() {return car;}public void setCar(Car car) {this.car = car;}@Overridepublic String toString() {return "Annotation [car=" + car + "]";}}
定義一個操作註解即讓註解起作用的類AnnotationProccessor類:
import java.lang.reflect.Field;public class AnnotationProccessor {public static void annoProcess(AnnotationDemo annotation){for(Field field : annotation.getClass().getDeclaredFields()){if(field.isAnnotationPresent(MyTag.class)){ //如果存在MyTag標籤MyTag myTag = field.getAnnotation(MyTag.class);annotation.setCar(new Car(myTag.name(),myTag.size()));}}}public static void main(String[] args) {AnnotationDemo ann = new AnnotationDemo();annoProcess(ann);System.out.println(ann.getCar());}}