Annotation註解

JDK5開始增加元數據支持,也就是Annotation

什麼是元數據:
元數據又稱中介數據、中繼數據,爲描述數據的數據,主要是描述數據屬性的信息。
第一次見在Python的Django中,我在創建表單/model的時候可以看到有個叫做Meta的東西,他涉及到Python的類創建,簡單的說就是給type()提供了一些變量和值。詳細原理http://blog.jobbole.com/21351/  
回到Java
~Annotation其實是代碼裏的特殊標記,它們可以在編譯、類加載、運行時被讀取,在不改變原有邏輯的情況下,在源文件中補充信息。有些工具可以通過這些信息可以通過這些信息驗證和部署。
Annotation,可以用來修飾包、類、構造器、方法、成員變量、參數、局部變量的聲明。
.../java/lang/annotation/ElementType.java
Annotation是一個接口,可以使用反射來獲取指定元素的Annotation對象,然後獲取元數據
~四個基本註解-J7+
@Override重寫/@Deprecated棄用/@SuppressWarnings抑制編譯警告/@SafeVarargs堆污染警告,在java.lang下
1、@Override
    用來只等方法重寫,強制一個子類必須重寫父類的方法。它告訴編譯器檢查這個方法,保證父類要包含一個被改方法重寫的方法,否則出錯。避免各種筆誤
2、@Deprecated
    用來表示某個元素(類、方法等)已經過時,使用時編譯器會警告
3、@SuppressWarnings
    取消顯示指定的編譯器警告,會作用於該程序的所有子元素
4、@SafeVarargs
    堆污染

      List list = new ArrayList<Integer>();

      list.add(10);

      List<String> temp = list;


~JDK的元Annotation
4個元註解用來修飾其他的Annotation定義
1. @Retention
保留時間
public enum RetentionPolicy {
/* Annotations are to be discarded by the compiler.* 編譯時丟棄/
SOURCE,
/* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.* 保留在calss文件中,JVM運行時丟棄/
CLASS,
/* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
* @see java.lang.reflect.AnnotatedElement 保留在class文件中,JVM運行時也會保留,用反射讀取*/
RUNTIME
}
2. @Target
修飾的目標
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal(adj.正式的;拘謹的;有條理的,[專業:形式{形參}]) parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**Type parameter declaration
* @since 1.8*/
TYPE_PARAMETER,
/**Use of a type
* @since 1.8*/
TYPE_USE
}
3. @Documented
將被javadoc工具提取成文檔
4. @Inherited
    子類將會繼承註解的修飾

~自定義Annotation

public @interface 名字{
[type name()[default value];//成員變量以方法的形式來定義]...
}

根據Annotation是否包含成員變量可以分成2種。
1、標記Annotation:沒有定義成員變量,利用自身存在與否提供信息如@Override
2、元數據Annotation:包含成員變量

~提取Annotation

(1)利用對象調用getClass()方法獲得Class實例

(2)利用Class類的靜態的forName()方法,使用類名獲得Class實例

(3)運用.class的方式獲得Class實例,如:類名.class

//類對象.getClass().getMethod("必須是用public標識的方法").getAnnotations())

Annotation[] aArray = Class.forName("類名").getMethod("必須是public標識的方法").getAnnotations();

但是要注意的是隻有public標識的纔可以,包括默認包行爲的都不可以

to be continue;



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章