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?

2
  • this question is already answered here Commented Dec 5, 2016 at 9:23
  • Just like you get the annotation from an arbitrary field. Commented Dec 5, 2016 at 15:39

2 Answers 2

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 "";
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
Yup, that is indeed the cause. The default retention policy is CLASS, i.e. the annotation will not be available for inspection at runtime.
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?

2 Comments

Can you tell me wich Field i have to import? Thx.
java.lang.reflect.Field

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.