【问题标题】:Get annotation for enum type获取枚举类型的注释
【发布时间】:2021-09-16 10:22:38
【问题描述】:

如何获取 SemanticId 注释值?:

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

【问题讨论】:

  • SomeEnum.class.getAnnotation(SemanticId.class).value().

标签: java kotlin reflection enums


【解决方案1】:

对于 Java:

    SomeEnum.class
              .getAnnotation(SemanticId.class)
              .value()

对于 Kotlin:

SomeEnum.annotations
                .filterIsInstance(SemanticId::class.java)
                .map { it.value }
                .firstOrNull()

【讨论】:

  • 两个sn-ps都不正确:第一个不需要value(),第二个不需要::class操作符获取KClass。
【解决方案2】:

Dmytro's answer 中的两个 sn-ps 都不正确。

首先SemanticId必须有注解保留RUNTIME否则无法通过反射获得。

通过反射获取其实例的三种方式:

Java 反射:

SemanticId myId = SomeEnum.class.getAnnotation(SemanticId.class);

Kotlin 中使用的 Java 反射:

val myId = SomeEnum::class.java.getAnnotation(SemanticId::class.java)

需要额外依赖 kotlin-reflect.jar 的 Kotlin 反射(解释为 here):

val myId = SomeEnum::class.findAnnotation<SemanticId>()

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 2020-11-29
    • 2020-10-29
    • 2017-01-14
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多