Java中提供了Annotation功能,该功能可用于类、构造方法、成员变量、方法、参数等的声明中。该功能并不影响程序的运行,但是对编译器等辅助工具产生影响。
定义Annotation类型
在定义Annotation类型时,也需要用到用来定义接口的interface关键字,但需要在interface关键字前加一个“@”
符号,即定义Annotation类型的关键字为@interface
,这个关键字隐含的意思是继承了java.long.annotation.Annotation
-接口
public @interface MoreMemberAnnotation {
String value();
Class type();
}
- String: 成员类型。可用的成员类型有String、Class、primitive、enumerated和annotation,以及所列类型的数组。
- value: 成员名称。如果所定义的Annotation类型中只包含一个成员,通常将成员名称命名为value。
在为Annotation类型定义成员时,也可以为成员设置默认值。例如,下面的代码在定义Annotation类型时就为成员设置了默认值。
public @interface MoreMemberAnnotation {
String value() default "默认值";
Class type() default void.class;
}
在定义Annotation类型时,还可以通过Annotation类型@Target来设置Annotation类型适用的程序元素种类。如果未设置@Target,则表示适用于所有程序元素。枚举类ElementType中的枚举通常用来设置@Target,如下表:
枚举常量 | 说明 |
---|---|
ANNOTATION_TYPE | 表示用于Annotation类型 |
TYPE | 用于表示类、接口和枚举,以及Annotation类型 |
CONSTRUCTOR | 表示用于构造方法 |
FIELD | 表示用于成员变量和枚举常量 |
METHOD | 表示用于方法 |
PARAMETER | 表示用于参数 |
LOCAL_VARIVBLE | 表示用于局部变量 |
PACKAGE | 表示用于包 |
通过Annotation类型@Retention可以设置Annotation的有效范围。枚举类RetentionPolicy中的枚举常量用来设置@Retention,如下表所示。如果未设置@Retention,Annotation的有效范围为枚举常量CLASS表示的范围。
枚举常量 | 说明 |
---|---|
SOURCE | 表示不编译Annotation到文件夹中,有效范围最小 |
CLASS | 表示编译Annotation到类文件中 |
RUNTIME | 表示在运行时加载Annotation到JVM中,有效范围最大 |
package zhao;
import java.lang.annotation.*;
@Target(ElementType.CONSTRUCTOR)
//用于构造方法
@Retention(RetentionPolicy.RUNTIME)
//在运行时加载Annotation到JVM中
public @interface Constructor_Annotation {
String value() default "默认构造方法";//定义一个具有默认值的String型成员
}
package zhao;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
//用于字段、方法和参数
@Retention(RUNTIME)
//在运行加载Annotation到JVM中
@Target({
FIELD, METHOD, PARAMETER })
public @