499. Java 反射 - 获取类型上的注解

499. Java 反射 - 获取类型上的注解

1. 背景介绍

  • Java 8 引入了 TYPE_USE 注解目标 ,意味着注解不仅可以标记在类、方法、字段上,还可以直接标记在类型使用的位置。
  • 举例:继承、实现接口、方法参数、返回值、异常声明等地方都可以放置注注解。
  • 为了支持这种能力,反射 API 提供了 AnnotatedType 接口,用来访问类型上的注解。

2. 定义一个 @NonNull 注解

java 复制代码
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
@interface NonNull {}

这里用 TYPE_USE 表示:注解可以用在"类型使用"的地方,而不是仅仅在"类型定义"上。


3. 在类型使用上应用注解

java 复制代码
public class Person {}

public class User
        extends @NonNull Person
        implements @NonNull Serializable {}

👉 这里:

  • User 继承了 @NonNull Person
  • User 实现了 @NonNull Serializable

4. 使用反射获取类型注解

java 复制代码
Class<?> c = User.class;

// 获取父类上的注解
AnnotatedType superClass = c.getAnnotatedSuperclass();
for (Annotation annotation : superClass.getAnnotations()) {
    System.out.println("annotation on the super class = " + annotation);
}

// 获取接口上的注解
AnnotatedType[] interfaces = c.getAnnotatedInterfaces();
for (AnnotatedType annotatedInterface : interfaces) {
    for (Annotation annotation : annotatedInterface.getAnnotations()) {
        System.out.println("annotation on the implemented interface = " + annotation);
    }
}

运行结果:

java 复制代码
annotation on the super class = @org.devjava.NonNull()
annotation on the implemented interface = @org.devjava.NonNull()

💡 要点:

  • getAnnotatedSuperclass():查看父类上的类型注解。
  • getAnnotatedInterfaces():查看接口上的类型注解。

5. 在异常声明上使用注解

有时我们希望给异常类型本身加注解,比如告诉调用者某个异常可以安全地转化为 RuntimeException。

定义注解

java 复制代码
@Target(ElementType.TYPE_USE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ReThrowAsRuntimeException {}

在构造器上使用

java 复制代码
class EmptyStringException extends Exception {
    public EmptyStringException(String message) {
        super(message);
    }
}

public class Message {
    private final String name;

    public Message(String name) throws @ReThrowAsRuntimeException EmptyStringException {
        if (name == null || name.isEmpty()) {
            throw new EmptyStringException("name is empty");
        }
        this.name = name;
    }
}

6. 客户端代码示例

java 复制代码
try {
    Message message = new Message(""); // 会触发异常
} catch (EmptyStringException e) {
    Constructor<?> constructor = Message.class.getConstructor(String.class);

    AnnotatedType[] exceptionTypes = constructor.getAnnotatedExceptionTypes();
    for (AnnotatedType exceptionType : exceptionTypes) {
        if (exceptionType.isAnnotationPresent(ReThrowAsRuntimeException.class)) {
            throw new RuntimeException(e); // 自动包装成运行时异常
        }
    }
}

运行结果:

java 复制代码
Exception in thread "main" java.lang.RuntimeException: org.devjava.EmptyStringException: name is empty
Caused by: org.devjava.EmptyStringException: name is empty

7. 总结

  • 普通注解 用在类、方法、字段;类型注解用在"类型使用"的地方。
  • 使用反射时:
    • getAnnotatedSuperclass() → 父类的类型注解
    • getAnnotatedInterfaces() → 接口的类型注解
    • getAnnotatedExceptionTypes() → 异常类型的注解
  • 这种能力非常适合做 代码质量检查、契约验证 (比如 @NonNull)、以及 异常处理策略 (比如 @ReThrowAsRuntimeException)。
相关推荐
FungLeo8 小时前
成为全栈·React 管理后台篇·总复盘:从“接口能调通”到“后台值得使用”
前端·react.js·前端框架·项目复盘·成为全栈
EatFan8 小时前
Spring Boot 4 落地观察:从 yudao-cloud、matecloud、JPower 看国产脚手架的升级路线与迁移清单
java·spring boot·后端·spring cloud·微服务·后端开发·jdk 21
Csvn9 小时前
并发模式:让渲染学会排队、插队和让路
前端
可乐鸡翅yeah_10 小时前
新手梳理:M3U8 线上问题,哪些是前端锅,哪些是后端锅
前端·ios·音视频·实时音视频·m3u8·音视频在线播放
Flynt10 小时前
Linear 用 1000 个 PR 换掉 styled-components,我写了 200 个按钮,把这笔账复现了一遍
前端·css·preact
波力海苔夹心脆67510 小时前
C# 序列化与反序列化详解:System.Text.Json、Newtonsoft.Json、XmlSerializer 用法、特性选项与安全实践
经验分享·后端·c#·json·.net
JavaGuide11 小时前
NVIDIA 又开源了!这次给 AI Agent 加上权限管控
前端·后端
excel11 小时前
prisma 如何处理数据库竞态
前端·数据库·后端
莪_幻尘12 小时前
Skill 体检:30 个 Skill 全凭感觉?体检器先自曝了 8 个“假 0 分
前端·人工智能·llm