如何获取成员变量的注释? [英] How to get annotations of a member variable?
问题描述
我想知道一个类的一些成员变量的注释,我使用 BeanInfo beanInfo = Introspector.getBeanInfo(User.class)
来内省一个类,并使用 BeanInfo.getPropertyDescriptors()
,查找特定属性,并使用 Class type = propertyDescriptor.getPropertyType()
获取属性的 Class .
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 ?
我尝试了 type.getAnnotations()
和 type.getDeclaredAnnotations()
,但都返回类的注释,而不是我想要的.例如:
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
{
...
}
我想获得地址的注释:@Column,而不是类地址的注释(@Entity、@Table、@Cache).如何实现?谢谢.
I want to get the address's annotation : @Column , not class Address's annotations (@Entity , @Table , @Cache) . How to achieve it ? Thanks.
推荐答案
for(Field field : cls.getDeclaredFields()){
Class type = field.getType();
String name = field.getName();
Annotation[] annotations = field.getDeclaredAnnotations();
}
另见:http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html
这篇关于如何获取成员变量的注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!