调用class.forname加载类后得到class对象,可用getannotation()获取指定运行时注解,需注解声明@retention(runtime);getannotations()和getdeclaredannotations()分别获取全部及直接声明的注解;注解属性通过方法调用获取,默认值自动返回。

调用 Class.forName 加载类后,得到的是一个 Class 对象,之后可以直接用反射 API 获取该类上声明的注解。
获取类上的特定注解
使用 getAnnotation(Class<t> annotationClass)</t> 方法,传入目标注解类型,返回该注解的实例(若存在)或 null(若不存在或未在运行时保留)。
注意:目标注解必须带有 @Retention(RetentionPolicy.RUNTIME),否则反射无法读取。
示例:
Class> clazz = Class.forName("com.example.MyService");
MyCustomAnnotation anno = clazz.getAnnotation(MyCustomAnnotation.class);
if (anno != null) {
System.out.println(anno.value()); // 假设注解有 value() 方法
}
获取类上所有注解
用 getAnnotations() 获取全部已声明且在运行时可见的注解数组;用 getDeclaredAnnotations() 获取本类直接声明(不含继承)的注解,两者行为在类注解场景下通常一致(因为 Java 类不支持注解继承)。
常见用法是遍历检查:
for (Annotation anno : clazz.getAnnotations()) {
if (anno instanceof MyCustomAnnotation) {
MyCustomAnnotation a = (MyCustomAnnotation) anno;
// 处理逻辑
}
}
处理注解中的属性值
注解本质是接口,其方法即为属性。通过调用对应方法即可获取值。若属性有默认值,未显式设置时会返回默认值。
支持的返回类型包括基本类型、String、Class、枚举、其他注解、以及上述类型的数组。
例如:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiVersion {
String value() default "v1";
int code() default 200;
Class> handler() default Void.class;
}
提取时:
ApiVersion av = clazz.getAnnotation(ApiVersion.class);
if (av != null) {
String ver = av.value(); // "v1" 或实际指定值
int code = av.code(); // 200 或实际指定值
Class> h = av.handler(); // Void.class 或具体类
}
注意事项与常见问题
确保以下几点,否则注解取不到:
- 注解定义中必须包含
@Retention(RetentionPolicy.RUNTIME) - 类路径正确,
Class.forName能成功加载(否则抛ClassNotFoundException) - 若类在模块化环境(Java 9+)中,目标包需对当前模块
opens或exports(仅当涉及私有成员反射时才需,类注解一般不受影响) - Spring 等框架可能对注解做了增强(如
AnnotationUtils),但原生反射已足够应对大多数场景
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











