温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么读取java注解

发布时间:2026-10-02 10:02:59 来源:亿速云 阅读:97 作者:小樊 栏目:编程语言

在 Java 中,“读取注解”通常叫做注解的解析(反射读取)。是否能读取到注解,取决于注解的生命周期(@Retention)。


一、先确认注解的 Retention

注解必须至少是:

@Retention(RetentionPolicy.RUNTIME)

否则运行期是读不到的。

示例:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value();
}

二、读取注解的三种位置

1️⃣ 读取【类】上的注解

Class<?> clazz = Demo.class;

if (clazz.isAnnotationPresent(MyAnnotation.class)) {
    MyAnnotation anno = clazz.getAnnotation(MyAnnotation.class);
    System.out.println(anno.value());
}

2️⃣ 读取【方法】上的注解

Method method = Demo.class.getMethod("test");

if (method.isAnnotationPresent(MyAnnotation.class)) {
    MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
    System.out.println(anno.value());
}

3️⃣ 读取【字段】上的注解

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 中的“读取注解”

如果你用的是 Spring:

AnnotationUtils.findAnnotation(bean.getClass(), MyAnnotation.class);

支持继承、组合注解,比原生反射更方便。


如果你愿意,可以告诉我:

  • 是 原生 Java / Spring / Android
  • 注解用在哪里(类 / 方法 / 字段)

我可以直接给你可复制的完整示例。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI
助
手