Richard Sand
Richard Sand

Reputation: 674

how to read runtime annotations on a field within a class

Imagine an annotation called "MyAnn" with runtime retention, a class MyClass, and an abstract class called MyData. MyClass has a field of type MyData, annotated with MyAnn. Within the instance of MyData, how do see if the annotation MyAnn is present and retrieve its information?

Note - in Java8 I know we can directly annotate the inner class at construction - and that works - but I need this working based on the field annotation.

Thanks for any help!

public MyClass extends MySuperClass() {
   @MyAnn(value = "something")
   protected MyData mydata;

   public void doSomething() {
      mydata = new MyData() {};
      mydata.initialize();
   }
}

public abstract MyData() {
   String myValue = null;

   public void initialize() {
      if (***I am annotated with MyAnn) {
         myValue = (***value from annotation MyAnn);         
      }
   }
}

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnn {
    String myvalue;
}

Upvotes: 1

Views: 856

Answers (1)

Mike Nakis
Mike Nakis

Reputation: 61949

MyData cannot directly know whether it has been annotated with MyAnn, because it has no knowledge of whether the current instance is a field or a standalone instance, and if it is a field, then whether the field has or has not been annotated with MyAnn.

So, you will need to somehow obtain and pass the value to initialize(), and you will need to somehow obtain the value at the place where initialize() is called. And from your code, it appears that "something" can be passed as a parameter to initialize(), making the whole thing a lot easier than annotating the field and then checking whether the field is annotated.

But in any case, if you want to check whether a field is annotated, you have to:

  • obtain the fields of your class with getClass().getDeclaredFields()

  • loop over the fields; for each field, either

    • invoke isAnnotationPresent( MyAnn.class ) or

    • invoke field.getAnnotations(), loop for each annotation, and check whether this annotation instanceof MyAnn.class

Once you have found the annotation, you can get its value with annotation.value();

Upvotes: 2

Related Questions