You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取枚举类上标注的SemanticId注解的取值

获取枚举类上标注的@SemanticId注解取值的方法

前提:需要确保@SemanticId注解本身配置了@Retention(RetentionPolicy.RUNTIME),保留到运行时才能通过反射读取到值。

你给出的示例枚举类如下:

@SemanticId("Something")
public enum SomeEnum {
    FIRST("First"),
    SECOND("Second")
}

基础实现代码

直接通过枚举类的Class对象调用getAnnotation方法即可读取:

// 获取枚举类上的SemanticId注解实例
SemanticId semanticIdAnno = SomeEnum.class.getAnnotation(SemanticId.class);
// 取注解的value属性值,此时取值为"Something"
String semanticId = semanticIdAnno.value();

空安全优化写法

如果不能保证枚举类一定加了该注解,可以加空值判断避免空指针:

// JDK8+ 用Optional链式处理
String semanticId = Optional.ofNullable(SomeEnum.class.getAnnotation(SemanticId.class))
        .map(SemanticId::value)
        .orElse(""); // 无注解时返回自定义默认值

通用工具方法

如果需要批量读取不同枚举类的该注解,可以封装通用工具方法:

/**
 * 读取枚举类上标注的@SemanticId值
 * @param enumClazz 目标枚举类Class对象
 * @return 注解取值,无注解或入参非法时返回null
 */
public static <T extends Enum<T>> String getEnumSemanticId(Class<T> enumClazz) {
    if (enumClazz == null || !enumClazz.isEnum()) {
        return null;
    }
    SemanticId anno = enumClazz.getAnnotation(SemanticId.class);
    return anno != null ? anno.value() : null;
}

// 调用示例
String result = getEnumSemanticId(SomeEnum.class);

补充说明

  • 上述方法仅适用于读取整个枚举类上的类级注解,如果要读取单个枚举值(比如示例中的FIRST、SECOND)上标注的@SemanticId,需要先获取枚举值对应的Field对象再读取注解
  • 如果@SemanticId注解存储取值的属性名不是value,把代码中的取值逻辑替换成对应属性的get方法即可

内容的提问来源于stack exchange,提问作者Dmytro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 22:12:01