在 Java 中,“读取注解”通常叫做注解的解析(反射读取)。是否能读取到注解,取决于注解的生命周期(@Retention)。
注解必须至少是:
@Retention(RetentionPolicy.RUNTIME)
否则运行期是读不到的。
示例:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
String value();
}
Class<?> clazz = Demo.class;
if (clazz.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation anno = clazz.getAnnotation(MyAnnotation.class);
System.out.println(anno.value());
}
Method method = Demo.class.getMethod("test");
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
System.out.println(anno.value());
}
Field field = Demo.class.getDeclaredField("name");
if (field.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation anno = field.getAnnotation(MyAnnotation.class);
System.out.println(anno.value());
}
for (Method m : Demo.class.getDeclaredMethods()) {
MyAnnotation anno = m.getAnnotation(MyAnnotation.class);
if (anno != null) {
System.out.println(m.getName() + " => " + anno.value());
}
}
✅ 私有方法/字段要 setAccessible(true)
✅ 注解属性必须有默认值或用时赋值
✅ 编译期注解(SOURCE)和类加载期(CLASS)读不到
如果你用的是 Spring:
AnnotationUtils.findAnnotation(bean.getClass(), MyAnnotation.class);
支持继承、组合注解,比原生反射更方便。
如果你愿意,可以告诉我:
我可以直接给你可复制的完整示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。