检索枚举的注释值

Retrieve value of annotation for an enum

我有这些注释:

@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();
}

但也许有人可以展示如何在 getKeygetValue 方法中检索注释?

首先,您需要将 runtime retention 添加到注释中,以便可以使用反射读取它们:

@Retention(RetentionPolicy.RUNTIME)
@interface NotNull {
    boolean value() default false;
}

@Retention(RetentionPolicy.RUNTIME)
@interface Type {
    Class<?> value();
}

然后您可以使用反射来获取将枚举常量视为 class 字段的注释:

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)]