如何获取成员变量的注释?

sma*_*ufo 56 java reflection annotations beaninfo

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

但我不知道如何将注释添加到成员变量中?

我试过了type.getAnnotations(),type.getDeclaredAnnotations()但是,两者都返回了Class的注释,而不是我想要的.例如 :

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 
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

我想得到地址的注释:@Column,而不是类地址的注释(@ Entity,@ Table,@ Cache).怎么实现呢?谢谢.

小智 79

每个人都描述了获取注释的问题,但问题在于注释的定义.您应该添加到注释定义中@Retention(RetentionPolicy.RUNTIME):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
    int id();
}
Run Code Online (Sandbox Code Playgroud)


Lau*_*ves 75

for(Field field : cls.getDeclaredFields()){
  Class type = field.getType();
  String name = field.getName();
  Annotation[] annotations = field.getDeclaredAnnotations();
}
Run Code Online (Sandbox Code Playgroud)

另见:http://docs.oracle.com/javase/tutorial/reflect/class/classMembers.html


Mar*_*ças 12

如果您需要知道是否存在特定注释.你可以这样做:

    Field[] fieldList = obj.getClass().getDeclaredFields();

        boolean isAnnotationNotNull, isAnnotationSize, isAnnotationNotEmpty;

        for (Field field : fieldList) {

            //Return the boolean value
            isAnnotationNotNull = field.isAnnotationPresent(NotNull.class);
            isAnnotationSize = field.isAnnotationPresent(Size.class);
            isAnnotationNotEmpty = field.isAnnotationPresent(NotEmpty.class);

        }
Run Code Online (Sandbox Code Playgroud)

等等其他注释......

我希望能帮助别人.


mko*_*yak 8

您必须使用反射来获取类的所有成员字段User,迭代它们并找到它们的注释

这样的事情:

public void getAnnotations(Class clazz){
    for(Field field : clazz.getDeclaredFields()){
        Class type = field.getType();
        String name = field.getName();
        field.getDeclaredAnnotations(); //do something to these
    }
}
Run Code Online (Sandbox Code Playgroud)


Lau*_*ves 5

您可以获取getter方法的注释:

propertyDescriptor.getReadMethod().getDeclaredAnnotations();
Run Code Online (Sandbox Code Playgroud)

获取私有字段的注释似乎是个坏主意......如果属性甚至没有字段支持,或者由具有不同名称的字段支持,该怎么办?即使忽略这些情况,你也会通过查看私人内容来打破抽象.

  • 嗨,因为我们的代码遵循了很多JPA的教程.大多数JPA教程/书籍直接在私有字段中添加注释.我想要挖掘的是这些JPA注释. (3认同)