Java中的Annotation 在流行的框架中用的越來越多,所以對註解的原理大概介紹一下,Java5以後就開始支持註解,所以到今天註解已經成爲元老級技術
我們使用@interface來定義註解,它其實跟class 、interface 、enum都類似,用來標識類型。Java中annotation包下提供了這幾個註解,類,接口,另外java.lang包下面又提供了五個註解
下面挨個看一下他們的源碼註釋基本就對註解有個瞭解了
一 Annotation接口
/**
* The common interface extended by all annotation types. Note that an
* interface that manually extends this one does <i>not</i> define
* an annotation type. Also note that this interface does not itself
* define an annotation type.
* @author Josh Bloch
* @since 1.5
*/
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
/**
* Returns the annotation type of this annotation.
* @return the annotation type of this annotation
*/
Class<? extends Annotation> annotationType();
}
所有註解都是基於此接口擴展,差不多他就是所有註解類型的父類,基類,祖先。。。但是請注意,自己寫一個類或接口繼承這個接口,自己寫的這個並不是註解類型,同時這個接口本身也不是一個註解(很繞),如何定義註解後面介紹。爲什麼說它是所有註解的基類呢,看下圖,在ieda開發工具中,點擊實現的小圖標,所有的註解就都出來了
再看它裏面有四個方法,前三個我們都很屬性,主要看第四個annotationType,返回這個註解的類型,這個先知道有這麼個方法,後面有用
二 AnnotationFormatError
public class AnnotationFormatError extends Error {
private static final long serialVersionUID = -4256701562333669892L;
public AnnotationFormatError(String message) {
super(message);
}
public AnnotationFormatError(String message, Throwable cause) {
super(message, cause);
}
public AnnotationFormatError(Throwable cause) {
super(cause);
}
}
當 annotation parser 註解解析器從類裏面讀取註解解析報錯的時候會拋出這個錯誤
三 @Documented,@Repeatable,@Retention,@Target
這幾個個都是元註解,就是用來聲明註解類型時需要使用到的註解
@Documented加上這個註解後,表明這個註解應該被 javadoc工具記錄,默認情況下,javadoc是不包括註解的. 但如果聲明註解時指定了 @Documented,則它會被 javadoc 之類的工具處理, 所以註解類型信息也會被包括在生成的文檔中,是一個標記註解,沒有成員
@Inherited使用此註解聲明出來的自定義註解,在使用此自定義註解時,如果註解在類上面時,子類會自動繼承此註解,否則的話,子類不會繼承此註解。這裏一定要記住,使用Inherited聲明出來的註解,只有在類上使用時纔會有效,對方法,屬性等其他無效。
@Retention用來定義自定義註解的什麼週期,RetentionPolicy value();它裏面有個value屬性,是一個RetentionPolicy類型,共有三種取值,
source:自定義註解只保留在源文件,當Java文件編譯成class文件的時候,註解被遺棄;被編譯器忽略
class:自定義註解被保留到class文件,但jvm加載class文件時候被遺棄,這是默認的生命週期
runtime:自定義註解不僅被保存到class文件中,jvm加載class文件之後,仍然存在
@Target用來定義自定義註解的使用範圍,ElementType[] value();他也有一個value屬性,是個數組,說明可以指定多個,若@Target註解未指定value值,則表明被@Target修飾的註解可以用於任何範圍
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration 表明此註解可以用在類或接口上 */
TYPE,
/** Field declaration (includes enum constants)表明此註解可以用在成員屬性上 */
FIELD,
/** Method declaration 表明此註解可以用在方法上 */
METHOD,
/** Formal parameter declaration 表明此註解可以用在參數上*/
PARAMETER,
/** Constructor declaration 表明此註解可以用在構造方法上*/
CONSTRUCTOR,
/** Local variable declaration 表明此註解可以用在局部變量上*/
LOCAL_VARIABLE,
/** Annotation type declaration 表明此註解可以用在註解類型上*/
ANNOTATION_TYPE,
/** Package declaration 用於記錄java文件的package文件信息,package-info.java 文件爲包級文檔和包級別註釋提供一個地方*/
PACKAGE,
/**
* Type parameter declaration
* 類型參數聲明
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
* 類型使用聲明
* @since 1.8
*/
TYPE_USE
}
四 @Native,@Repeatable
爲jdk1.8以後提供,@Native用來標記native的屬性,只對屬性有效,且只在代碼中使用,一般用於給IDE工具做提示用。@Repeatable允許在同一申明類型(類,屬性,或方法)的多次使用同一個註解
下一節說一下註解的使用及工作原理