4

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?

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
Removed
  • 109
  • 3
  • 19
  • this question is already answered [here](http://stackoverflow.com/questions/12947125/calling-a-enum-value-from-another-class-within-the-same-java-project) – yaitloutou Dec 05 '16 at 09:23
  • Just like you get the annotation from an arbitrary field. – Holger Dec 05 '16 at 15:39

2 Answers2

3

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 "";
}
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • Is `@Retention(RetentionPolicy.RUNTIME)` the reason for getting a NullPointer with my code? I mean could you elaborate the use and reason to use it more. – Naman Dec 05 '16 at 09:42
  • 1
    Yup, that is indeed the cause. The default retention policy is [`CLASS`](https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/RetentionPolicy.html#CLASS), i.e. the annotation will not be available for inspection at runtime. – Robby Cornelissen Dec 05 '16 at 09:43
1

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?

Community
  • 1
  • 1
Naman
  • 27,789
  • 26
  • 218
  • 353