Search code examples
javaenumsannotationsenumerator

Get annotation value from enum constant


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?


Solution

  • 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 "";
    }