模式切换
注解
使用 Annotation 功能
Annotation 是 Java 5 引入的一种注解机制,用于为程序元素(类、方法、字段等)添加元数据。Annotation 本身并不影响程序的运行,但可以通过反射机制读取 Annotation 信息,从而实现一些功能。
定义 Annotation 时,需要使用 @interface
关键字。Annotation 中可以包含成员变量,成员变量的类型可以是基本数据类型、String
、Class
、enum
、Annotation
或以上类型的数组。
在定义 Annotation 时,通过 @Target
设置 Annotation 的作用范围,如果不设置,则默认作用于所有程序元素。
还可以通过 @Retention
设置 Annotation 的生命周期,如果不设置,则默认为 RetentionPolicy.CLASS
。
表 ElementType 中的枚举常量
表 RetentionPolicy 中的枚举常量
在下面的示例中,定义了一个 MyAnnotation
注解,用于标记方法,在运行时保留。并在 Test
类的 testMethod()
方法上应用了 MyAnnotation
注解。
java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) // 运行时保留
@Target(ElementType.METHOD) // 作用于方法
@interface MyAnnotation {
String value();
}
java
class Test {
@MyAnnotation("Hello Annotation")
public void testMethod() {
System.out.println("Executing testMethod()");
}
}
访问 Annotation 信息
如果在定义 Annotation 类型时将 @Retention
设置为 RetentionPolicy.RUNTIME
,则可以在运行时通过反射机制获取 Annotation 信息,例如获取构造方法、字段、方法上的 Annotation 信息。
类 Constructor
、Field
和 Method
都继承自 AccessibleObject
类,AccessibleObject
类中提供了方法用于获取 Annotation 信息。
isAnnotationPresent(Class<? extends Annotation> annotationClass)
:判断是否存在指定类型的 Annotation,存在则返回true
。getAnnotation(Class<T> annotationClass)
:获取指定类型的 Annotation,存在则返回 Annotation 对象,否则返回null
。getAnnotations()
:获取所有 Annotation,返回 Annotation 数组。
在类 Constructor
和 Method
中,还提供了 getParameterAnnotations()
方法用于获取参数上的 Annotation,返回一个 Annotation 类型的二维数组。在数组中的顺序与声明的顺序相同,如果没有参数则返回一个长度为 0 的数组,如果存在未添加 Annotation 的参数,将用一个长度为 0 的嵌套数组占位。
在下面的示例中,通过反射机制获取 Test
类的 testMethod()
方法上的 MyAnnotation
注解信息:
java
import java.lang.reflect.Method;
public class AnnotationDemo {
public static void main(String[] args) throws Exception {
Class<?> clazz = Test.class;
Method method = clazz.getMethod("testMethod");
// 判断方法上是否存在 MyAnnotation
if (method.isAnnotationPresent(MyAnnotation.class)) {
// 获取 Annotation 信息
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Annotation Value: " + annotation.value());
}
}
}