简体   繁体   English

如何使用反射在Java中获取注释的属性?

[英]How to get attributes of annotations in Java using reflection?

I have several data classes in java of which I want to know - using reflection - which fields have a certain annotation with a certain attribute which is the following:我在java中有几个我想知道的数据类 - 使用反射 - 哪些字段具有具有特定属性的特定注释,如下所示:

@Column(columnDefinition = "text") // Text with unbound length
private String comment;

I figured how to get the annotations of the field and whether it is of type Column :我想出了如何获取该字段的注释以及它是否属于Column类型:

private boolean isStringFieldWithBoundLength(Field attr) {
    Annotation[] annotations = attr.getDeclaredAnnotations();
    for (Annotation ann : annotations) {
        Class<? extends Annotation> aClass = ann.annotationType();
        if (Column.class == aClass) {
            
            // ...
            
        }
    }
}

Now in the debugger I can see that the aClass object has the information about the provided parameters.现在在调试器中,我可以看到aClass对象包含有关所提供参数的信息。 Unfortunately I don't know how to access it with code.不幸的是,我不知道如何使用代码访问它。 Is it possible to access this information in java?是否可以在 java 中访问这些信息?

You should be able to get the instance of that annotation (including your values) using您应该能够使用获取该注释的实例(包括您的值)

Column fieldAnnotation = attr.getAnnotation(Column.class);

If the field is not annotated with @Column , getAnnotation returns null.如果该字段未使用@Column注释, getAnnotation返回 null。 That means you don't need to iterate over attr.getDeclaredAnnotations();这意味着您不需要遍历attr.getDeclaredAnnotations();

You can then call fieldAnnotation.columnDefinition() or whatever custom field that your annotation might have.然后,您可以调用fieldAnnotation.columnDefinition()或您的注释可能具有的任何自定义字段。

Addition: your annotation needs to have @Retention(RetentionPolicy.RUNTIME) for that to work, otherwise your annotations will be removed from classes/fields/methods during compilation.另外:您的注释需要有@Retention(RetentionPolicy.RUNTIME)才能工作,否则您的注释将在编译期间从类/字段/方法中删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM