I have an enumerator and a custom annotation that represents the enumerator's description:
public @interface Description {
String name() default "";
}
Enumerator:
public enum KeyIntermediaryService {
@Description(name="Descrizione WorldCheckService")
WORLDCHECKSERVICE,
@Description(name="blabla")
WORLDCHECKDOWNLOAD,
@Description(name="")
WORLDCHECKTERRORISM,
// ...
}
How can I get the enumerator description from within another class?
Like this, e.g. to get the description for the WORLDCHECKSERVICE
enum value:
Description description = KeyIntermediaryService.class
.getField(KeyIntermediaryService.WORLDCHECKSERVICE.name())
.getAnnotation(Description.class);
System.out.println(description.name());
You would have to change your annotation's retention policy to runtime though:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Description {
String name() default "";
}
Followed the link Is it possible to read the value of a annotation in java? to produce the following code -
public static void main(String[] args) {
for (Field field : KeyIntermediaryService.class.getFields()) {
Description description = field.getAnnotation(Description.class);
System.out.println(description.name());
}
}
Ya but this code would produce an NPE, unless as specifed by @Robby in his answer that you need to change your annotation to have a @Retention(RetentionPolicy.RUNTIME)
marked for Description
.
The reason for that being stated in the answer here - How do different retention policies affect my annotations?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With