java 如何读取注解
读取注解的方法
在Java中,读取注解主要通过反射机制实现。以下是几种常见场景下的操作方法:
读取类上的注解
使用Class对象的getAnnotation()或getAnnotations()方法:
// 定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyClassAnnotation {
String value();
}
// 使用注解
@MyClassAnnotation("示例类")
public class MyClass {}
// 读取注解
Class<?> clazz = MyClass.class;
MyClassAnnotation annotation = clazz.getAnnotation(MyClassAnnotation.class);
if (annotation != null) {
System.out.println(annotation.value()); // 输出:示例类
}
读取方法上的注解
通过Method对象获取方法注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyMethodAnnotation {
int priority() default 0;
}
public class MyClass {
@MyMethodAnnotation(priority = 1)
public void myMethod() {}
}
// 读取方法注解
Method method = MyClass.class.getMethod("myMethod");
MyMethodAnnotation methodAnnotation = method.getAnnotation(MyMethodAnnotation.class);
System.out.println(methodAnnotation.priority()); // 输出:1
读取字段上的注解
通过Field对象获取字段注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyFieldAnnotation {
boolean required() default true;
}
public class MyClass {
@MyFieldAnnotation(required = false)
private String myField;
}
// 读取字段注解
Field field = MyClass.class.getDeclaredField("myField");
MyFieldAnnotation fieldAnnotation = field.getAnnotation(MyFieldAnnotation.class);
System.out.println(fieldAnnotation.required()); // 输出:false
读取参数上的注解
通过Parameter对象获取参数注解(需Java 8+):
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface MyParamAnnotation {
String name();
}
public class MyClass {
public void myMethod(@MyParamAnnotation(name = "param1") String param) {}
}
// 读取参数注解
Method method = MyClass.class.getMethod("myMethod", String.class);
Parameter parameter = method.getParameters()[0];
MyParamAnnotation paramAnnotation = parameter.getAnnotation(MyParamAnnotation.class);
System.out.println(paramAnnotation.name()); // 输出:param1
检查注解是否存在
使用isAnnotationPresent()方法:

if (MyClass.class.isAnnotationPresent(MyClassAnnotation.class)) {
// 注解存在的处理逻辑
}
注意事项
- 注解的
@Retention必须设置为RetentionPolicy.RUNTIME,否则运行时无法读取。 - 读取私有字段/方法时需先调用
setAccessible(true)。 - 性能敏感场景慎用反射,可考虑注解处理器(APT)或运行时字节码增强方案。
完整示例
// 定义注解
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Author {
String name();
String date();
}
// 使用注解
@Author(name = "John", date = "2023-10-01")
public class Document {
@Author(name = "Jane", date = "2023-10-02")
public void save() {}
}
// 读取所有注解
public class AnnotationReader {
public static void main(String[] args) throws Exception {
Class<?> docClass = Document.class;
// 读取类注解
Author classAuthor = docClass.getAnnotation(Author.class);
System.out.println("Class author: " + classAuthor.name());
// 读取方法注解
Method saveMethod = docClass.getMethod("save");
Author methodAuthor = saveMethod.getAnnotation(Author.class);
System.out.println("Method author: " + methodAuthor.name());
}
}






