java - 检索枚举的注释值
问题描述
我有这些注释:
@interface NotNull {
boolean value() default false;
}
@interface Type {
Class<?> value();
}
然后我将它们与枚举一起使用:
public enum KeyMap implements IMapEnum {
@Type(Integer.class)
@NotNull
USER_ID("user_id", "userId"),
@NotNull
USER_HANDLE("user_handle", "userHandle"),
@NotNull
USER_EMAIL("user_email", "userEmail");
private String key;
private String value;
KeyMap(String k, String v) {
this.key = k;
this.value = v;
}
@Override
public String getKey() {
return this.key;
}
@Override
public String getValue() {
return this.value;
}
}
我的问题是 - 如何检索每个枚举实例的注释值?正在实现的接口很简单,并不是问题的一部分:
public interface IMapEnum {
String getKey();
String getValue();
}
但也许有人可以展示如何在其中一个getKey
或getValue
方法中检索注释?
解决方案
首先,您需要将运行时保留添加到您的注释中,以便可以使用反射读取它们:
@Retention(RetentionPolicy.RUNTIME)
@interface NotNull {
boolean value() default false;
}
@Retention(RetentionPolicy.RUNTIME)
@interface Type {
Class<?> value();
}
然后您可以使用反射来获取将枚举常量视为类字段的注释:
Field field = KeyMap.class.getField(KeyMap.USER_ID.name());
Annotation[] annotations = field.getDeclaredAnnotations();
System.out.println(Arrays.toString(annotations));
将打印:
[@Type(value=java.lang.Integer.class), @NotNull(value=false)]
推荐阅读
- java - 需要 java OOP 和数组
- javascript - 使用 Intersection Observer API 延迟翻译元素
- python - Guru Meditation Error: Core 1 panic'ed (Double exception) ESP32 using MQTT
- html - 在视口中调整图像
- node.js - 使用 mongoose nodejs 在另一个集合 mongoDB 中填充集合
- docker - 带大使 API 网关的 Go 微服务
- sql - 数据库结构 - 通过外键和求和填充表
- python - 要求用户输入文件以使用 python 运行程序
- typescript - typescript 3.33的onClick问题并做出反应
- android - FirebaseUser currentUser 存在,在代码中,即使它是从 Firebase DB 中手动删除的