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.