处理注解
约 979 字大约 3 分钟
2025-07-17
Java 的注解本身对代码逻辑没有任何影响。注解的行为取决于其 @Retention
配置,主要有以下三种类型:
SOURCE
: 此类注解在编译期会被丢弃,通常由编译器使用。CLASS
: 此类注解仅保存在.class
文件中,不会被加载到 JVM,主要由底层工具库使用。RUNTIME
: 此类注解会被加载到 JVM,并在运行时可以通过程序读取。RUNTIME
类型的注解不仅会被使用,还经常需要我们自己编写。
本节主要讨论如何读取 RUNTIME
类型的注解。因为注解定义后也是一种 class
,所有的注解都继承自 java.lang.annotation.Annotation
,因此,读取注解需要使用反射 API。
3.1 使用反射 API 读取 Annotation
Java 提供了使用反射 API 读取 Annotation
的方法,包括判断注解是否存在以及获取注解信息。
判断某个注解是否存在于 Class
、Field
、Method
或 Constructor
:
Class.isAnnotationPresent(Class)
Field.isAnnotationPresent(Class)
Method.isAnnotationPresent(Class)
Constructor.isAnnotationPresent(Class)
例如:
// 判断 @Report 是否存在于 Person 类:
Person.class.isAnnotationPresent(Report.class);
使用反射 API 读取 Annotation:
Class.getAnnotation(Class)
Field.getAnnotation(Class)
Method.getAnnotation(Class)
Constructor.getAnnotation(Class)
例如:
// 获取 Person 定义的 @Report 注解:
Report report = Person.class.getAnnotation(Report.class);
int type = report.type();
String level = report.level();
使用反射 API 读取 Annotation
有两种方式:
先判断
Annotation
是否存在,如果存在,则直接读取:Class cls = Person.class; if (cls.isAnnotationPresent(Report.class)) { Report report = cls.getAnnotation(Report.class); ... }
直接读取
Annotation
,如果Annotation
不存在,将返回null
:Class cls = Person.class; Report report = cls.getAnnotation(Report.class); if (report != null) { ... }
读取方法、字段和构造方法的 Annotation
与 Class 类似。然而,读取方法参数的 Annotation
较为复杂,因为方法参数本身可以看作一个数组,而每个参数又可以定义多个注解。因此,一次性获取方法参数的所有注解需要使用一个二维数组来表示。例如,对于以下方法定义的注解:
public void hello(@NotNull @Range(max=5) String name, @NotNull String prefix) {
}
要读取方法参数的注解,首先需要通过反射获取 Method
实例,然后读取方法参数的所有注解:
// 获取 Method 实例:
Method m = ...
// 获取所有参数的 Annotation:
Annotation[][] annos = m.getParameterAnnotations();
// 第一个参数(索引为 0)的所有 Annotation:
Annotation[] annosOfName = annos[0];
for (Annotation anno : annosOfName) {
if (anno instanceof Range r) { // @Range 注解
r.max();
}
if (anno instanceof NotNull n) { // @NotNull 注解
//
}
}
接下来,我们将通过一个示例来展示如何使用自定义注解来实现特定的功能。
3.2 使用注解
注解的使用完全取决于程序本身。例如,JUnit 是一个测试框架,它会自动运行所有标记为 @Test
的方法。现在,假设我们有一个 @Range
注解,用于定义 String
字段的规则,即字段长度必须满足 @Range
的参数定义:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Range {
int min() default 0;
int max() default 255;
}
在某个 JavaBean 中,我们可以使用该注解:
public class Person {
@Range(min=1, max=20)
public String name;
@Range(max=10)
public String city;
}
需要注意的是,定义注解本身对程序逻辑没有任何影响。我们需要编写代码来使用注解。以下是一个 Person
实例的检查方法,用于检查 Person
实例的 String
字段长度是否满足 @Range
的定义:
void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {
// 遍历所有 Field:
for (Field field : person.getClass().getFields()) {
// 获取 Field 定义的 @Range:
Range range = field.getAnnotation(Range.class);
// 如果 @Range 存在:
if (range != null) {
// 获取 Field 的值:
Object value = field.get(person);
// 如果值是 String:
if (value instanceof String s) {
// 判断值是否满足 @Range 的 min/max:
if (s.length() < range.min() || s.length() > range.max()) {
throw new IllegalArgumentException("Invalid field: " + field.getName());
}
}
}
}
}
通过 @Range
注解,结合 check()
方法,我们可以完成 Person
实例的检查。需要注意的是,检查逻辑完全由我们自己编写,JVM 不会自动为注解添加任何额外的逻辑。