Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 978
Removed Avatar asked Sep 07 '25 15:09

Removed


2 Answers

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 "";
}
like image 197
Robby Cornelissen Avatar answered Sep 09 '25 08:09

Robby Cornelissen


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?

like image 36
Naman Avatar answered Sep 09 '25 08:09

Naman