I want to know a class's some member variable's annotations , I use BeanInfo beanInfo = Introspector.getBeanInfo(User.class)
to introspect a class , and use BeanInfo.getPropertyDescriptors()
, to find specific property , and use Class type = propertyDescriptor.getPropertyType()
to get the property's Class .
But I don't know how to get the annotations added to the member variable ?
I tried type.getAnnotations()
, and type.getDeclaredAnnotations()
, but both return the Class's annotations , not what I want . For example :
class User
{
@Id
private Long id;
@Column(name="ADDRESS_ID")
private Address address;
// getters , setters
}
@Entity
@Table(name = "Address")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
class Address
{
...
}
I want to get the address's annotation : @Column , not class Address's annotations (@Entity , @Table , @Cache) . How to achieve it ? Thanks.
getAnnotation(Class< T > annotationClass) method of Method class returns Method objects's annotation for the specified type passed as parameter if such an annotation is present, else null. This is important method to get annotation for Method object.
Annotations, just like methods or fields, can be inherited between class hierarchies. If an annotation declaration is marked with @Inherited , then a class that extends another class with this annotation can inherit it. The annotation can be overridden in case the child class has the annotation.
The getAnnotation() method of java. lang. Class class is used to get the annotation of the specified annotation type, if such an annotation is present in this class. The method returns that class in the form of an object.
You can Control-click on the annotation which will open the annotation definition class and then right-click and choose References -> Workspace . EDIT: I just checked it, and it is enough to right-click on the mentioned annotation and choosing References -> Workspace without even going into its definition.
for(Field field : cls.getDeclaredFields()){
Class type = field.getType();
String name = field.getName();
Annotation[] annotations = field.getDeclaredAnnotations();
}
See also: http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME)
:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
int id();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With