1

Before marking it duplicate, please note that this is very specific question with specific scenario and I have already search extensively the forum to get any clue towards answer. Please make sure that the query in this post is addressed completely in other thread before reporting it duplicated.

I have below scenario:

An annotation with RUNTIME retention plocy

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD) //can use in fields only.
public @interface TestAnnotation{
    public String id();
}

It is being used like

public class TestBean{
   @TestAnnotation(id="t1")
   private String test1;

   @TestAnnotation(id="t2")
   private String test2;
}

Now in other class, I am trying to get annotation value using

    for (PropertyDescriptor propDescriptor : Introspector.getBeanInfo(Class.forName("TestBean")).getPropertyDescriptors()) {
        Class<?> propertyType = propDescriptor.getPropertyType();
        TestAnnotation myAnno= propertyType.getAnnotation(TestAnnotation.class);

But the value of myAnno is coming as Null. However, if I use Class.forName("TestBean").getDeclaredFields()[1].getAnnotation(TestAnnotation.class); I am able to get the value. It means the RUNTIME retention is working.

All I need help with on how to use Bean Introspection to get the annotation. I do not wish to use getDeclaredFields, so kindly leave that as a possibility.

Gyanendra Dwivedi
  • 5,511
  • 2
  • 27
  • 53
  • 1
    `propertyType.getAnnotation` gets you the annotation on the class of `propertyType`, not the field. In this case it would go look for `@TestAnnotation` on `java.lang.String`, and of course would not find it there. – jingx Jun 12 '17 at 20:50
  • 1
    I second this. In your code propertyType will be Class, which is a class from standard java library and doesn't have any annotations like @TestAnnotation. – ekaerovets Jun 12 '17 at 20:52
  • 1
    Thanks, it is working as expected. just wanted to know, if there is anyway to get the annotation other than `getDeclaredFields` of private member. I am trying to respect Java privacy. – Gyanendra Dwivedi Jun 12 '17 at 21:50

0 Answers0