Java注解詳解
Java注解是JDK1.5以后添加的特性,自定義注解需要聲明為@interface。
最簡單的注解:
public @interface Demo {
}
定義注解時需要一些元注解
@Target 參數(shù)表示在什么地方使用該注解,一個方法或一個域等
CONSTRUCTOR: 構(gòu)造器申明
FIELD: 域申明
LOCAL_VARIABLE: 局部變量申明
METHOD: 方法申明
PACKAGE: 包申明
PARAMETER: 參數(shù)申明
TYPE: 類,接口或枚舉申明
源碼:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
/**
* Returns an array of the kinds of elements an annotation type
* can be applied to.
* @return an array of the kinds of elements an annotation type
* can be applied to
*/
ElementType[] value();
}
@Retention 用來定義該注解是哪一個級別可用:在源代碼中、類文件中、還是運(yùn)行時
沒有注解元素的注解稱為標(biāo)記注解
SOURCE: 注解被編譯器丟棄
CLASS: 注解在class文件中使用, 但會被JVM丟棄
RUNTIME: VM將在運(yùn)行期也保留注解, 因此可以通過反射機(jī)智讀取注解的信息
源碼:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
@Documented 表示將此注解包含在javadoc中
源碼:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Documented {
}
@Inherited 表示允許子類繼承父類中的注解
源碼:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Inherited {
}
注解元素可以使用所有的基本類型、String、Class、Annotation等使用其他的類型會報錯。