JDK 的元 Annotation
跳到导航
跳到搜索
@Retention
@Retention 只能用于修饰一个 Annotation 定义,用于指定被修饰的 Annotation 可以保留多长时间,@Retention 包含一个 RetentionPolicy 类型的 value 成员变量,所以使用 @Retention 时必须为该 value 成员变量指定值。
value 成员变量的值只能是如下 3 个。
- RetentionPolicy.CLASS 编译器将把 Annotation 记录在 class 文件中。当运行 Java 程序时,JVM不再保留 Annotation。这是默认值
- RetentionPolicy.RUNTIME 编译器将把 Annotation 记录在 class 文件中。当运行 Java 程序时,JVM 也会保留 Annotation,程序可以通过反射获取该 Annotation 信息。
- RetentionPolicy.SOURCE Annotation 只保留在源代码中,编译器直接丢弃这种 Annotation。
如果需要通过反射获取注释信息,就需要使用 value 属性值为 RetentionPolicy.RUNTIME 的 @Retention。
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//定义下面的 Testable Annotation 保留到运行时
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Testable {
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//定义下面的 Testable Annotation 将被编译器直接丢弃
@Retention(RetentionPolicy.SOURCE)
public @interface Testable1 {
}
@Target
@Target 也只能修饰一个 Annotation 定义,它用于指定被修饰的 Annotation 能用于修饰哪些程序单元。
@Target 元 Annotation 也包含一个名为 value 的成员变量,该成员变量的值只能是如下几个。
- ElementType.ANNOTATION_TYPE 制定该策略的 Annotation 只能修饰 Annotation。
- ElementType.CONSTRUCTOR 指定该策略 Annotation 只能修饰构造器。
- ElementType.FIELD 指定该策略的 Annotation 只能修饰成员变量。
- ElementType.LOCAL_VARIABLE 指定该策略的 Annotation 只能修饰局部变量。
- ElementType.METHOD 指定该策略的 Annotation 只能修饰方法定义。
- ElementType.PACKAGE 指定该策略的 Annotation 只能修饰包定义。
- ElementType.PARAMETER 指定该策略的 Annotation 可以修饰参数
- ElementType.TYPE 指定该策略的 Annotation 可以修饰类、接口(包括注释类型)或枚举定义。
与使用 @Retention 类似的是,使用 @Target 也可以直接在括号里指定 value 值,而无须使用 name=value 的形式。
如下代码指定 @ActionListenerFor Annotation 只能修饰成员变量。
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
public @interface ActionListenerFor {
}
如下代码片段指定 @Testable Annotation 只能修饰方法。
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
public @interface Testable2 {
}
@Document
@Document 用于指定被该元 Annotation 修饰的 Annotation 类将被 javadoc 工具提取成文档,如果定义 Annotation 类时使用了 @Documented 修饰,则所有使用该 Annotation 修饰的程序元素的 API 文档中将会包含该 Annotation 说明。