class.getdeclaredannotation(class annotationclass)用于获取直接声明在该类上的指定类型注解,仅限runtime保留策略,不继承、不支持@repeatable,返回null需判空。

Class.getDeclaredAnnotation(Class<t> annotationClass)</t> 用于获取**直接声明在该类上**(而非继承自父类或接口)的指定类型的注解,且只返回一个(如果存在),不包含重复注解(@Repeatable 的情况需用 getDeclaredAnnotationsByType)。
关键前提:注解必须是 RUNTIME 保留策略
只有当注解定义时使用了 @Retention(RetentionPolicy.RUNTIME),才能在运行时通过反射获取。若为 CLASS 或 SOURCE,调用此方法会始终返回 null。
- 检查你的注解是否标注了
@Retention(RetentionPolicy.RUNTIME) - 确认注解没有被其他编译期处理(如 Lombok)意外移除
只匹配“直接声明”,不继承
该方法不会查找父类、接口或超类上的同类型注解。例如:
@MyAnnotation
class Parent { }
class Child extends Parent { }
对 Child.class.getDeclaredAnnotation(MyAnnotation.class) 调用结果为 null,因为 @MyAnnotation 是声明在 Parent 上,而非 Child 本身。
- 若需查找包括继承链上的注解,改用
getAnnotation(Class<t>)</t> - 若明确只要当前类自己写的注解,才用
getDeclaredAnnotation
注意:不支持重复注解(@Repeatable)
如果注解被标记为可重复(@Repeatable),比如 @RolesAllowed("ADMIN", "USER") 可能出现多次,getDeclaredAnnotation 只会返回其中一个(通常第一个),且行为不确定。
- 正确方式是使用
getDeclaredAnnotationsByType(MyAnnotation.class) - 它返回
MyAnnotation[],能完整获取所有直接声明的同类型注解实例
典型使用示例
假设定义了如下注解和类:
@Retention(RetentionPolicy.RUNTIME)
@interface Version {
double value() default 1.0;
}
@Version(2.3)
public class UserService { }
获取方式:
Version version = UserService.class.getDeclaredAnnotation(Version.class);
if (version != null) {
System.out.println(version.value()); // 输出 2.3
}
- 返回值可能为
null,务必判空 - 不能用于字段、方法等成员——那是
Field.getDeclaredAnnotation()或Method.getDeclaredAnnotation() - 仅适用于
Class、Field、Method、Constructor等反射对象,但签名和语义略有差异
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











