从枚举常量中获取注解值

Get annotation value from enum constant

我有一个枚举器和一个表示枚举器描述的自定义注释:

public @interface Description {

   String name() default "";

}

枚举器:

public enum KeyIntermediaryService {
     @Description(name="Descrizione WorldCheckService")
     WORLDCHECKSERVICE,
     @Description(name="blabla")
     WORLDCHECKDOWNLOAD,
     @Description(name="")
     WORLDCHECKTERRORISM,
     // ...
}

如何从另一个 class 中获取枚举器描述?

像这样,例如获取 WORLDCHECKSERVICE 枚举值的描述​​:

Description description = KeyIntermediaryService.class
        .getField(KeyIntermediaryService.WORLDCHECKSERVICE.name())
        .getAnnotation(Description.class);

System.out.println(description.name());

不过您必须将注释的保留策略更改为运行时:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Description {
    String name() default "";
}

按照 link Is it possible to read the value of a annotation in java? 生成以下代码 -

public static void main(String[] args) {
     for (Field field : KeyIntermediaryService.class.getFields()) {
         Description description = field.getAnnotation(Description.class);
         System.out.println(description.name());
     }
}

是的,但是此代码会产生 NPE,除非 @Robby 在他的回答中指定您需要更改注释以将 @Retention(RetentionPolicy.RUNTIME) 标记为 Description

此处答案中说明的原因 - How do different retention policies affect my annotations?