我想知道一个类的一些成员变量的注解,我使用 BeanInfo beanInfo = Introspector.getBeanInfo(User.class)
来自省(introspection)一个类,并使用 BeanInfo.getPropertyDescriptors()
,查找具体的属性,并使用 Class type = propertyDescriptor.getPropertyType()
获取属性的 Class 。
但是我不知道如何将注解添加到成员变量中?
我尝试了 type.getAnnotations()
和 type.getDeclaredAnnotations()
,但都返回了类的注释,而不是我想要的。例如:
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)。如何实现呢?谢谢。
最佳答案
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
关于java - 如何获取成员变量的注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4453159/