本文介绍了如何获得一个成员变量的注解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道一个类的一些成员变量的注解,我用的BeanInfo的BeanInfo = Introspector.getBeanInfo(User.class)内省一个类,并使用 BeanInfo.getPropertyDescriptors(),找到特定的属性,并使用类键入= propertyDescriptor.getPropertyType()来获取属性的类。

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(),但都返回Class的注解,不是我想要的。例如:

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.

推荐答案

这是除了它的code mkoryak的变化不依赖于 Class.newInstance (和它编译)。

This is a variation of the code mkoryak except it doesn't rely on Class.newInstance (and it compiles).

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

这篇关于如何获得一个成员变量的注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 16:47