java - 如何使用反射获取注解类名、属性值

标签 java reflection annotations

我知道如果我们知道注释类,我们可以轻松获取特定的注释并访问其属性。例如:

field.getAnnotation(Class<T> annotationClass) 

它将返回特定注释接口(interface)的引用,以便您可以轻松访问其值。

我的问题是我是否对特定注释类没有预先了解。我只想使用反射在运行时获取所有注释类名称及其属性,以便将类信息转储为 JSON 文件。我怎样才能以简单的方式做到这一点。

Annotation[] field.getAnnotations();

该方法只会返回注解接口(interface)的动态代理。

最佳答案

与人们的预期相反,注释的元素不是属性 - 它们实际上是返回提供的值或默认值的方法。

您必须迭代注释的方法并调用它们来获取值。使用annotationType()获取注释的类,getClass()返回的对象只是一个代理。

这是一个打印 @Resource 的所有元素及其值的示例。类的注释:

@Resource(name = "foo", description = "bar")
public class Test {

    public static void main(String[] args) throws Exception {

        for (Annotation annotation : Test.class.getAnnotations()) {
            Class<? extends Annotation> type = annotation.annotationType();
            System.out.println("Values of " + type.getName());

            for (Method method : type.getDeclaredMethods()) {
                Object value = method.invoke(annotation, (Object[])null);
                System.out.println(" " + method.getName() + ": " + value);
            }
        }

    }
}

输出:

Values of javax.annotation.Resource
 name: foo
 type: class java.lang.Object
 lookup: 
 description: bar
 authenticationType: CONTAINER
 mappedName: 
 shareable: true

感谢 Aaron为了指出您需要转换 null 参数以避免警告。

关于java - 如何使用反射获取注解类名、属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61597149/

相关文章:

java - 有没有办法从 mysql 获取超出 ArrayList 最大大小的记录

java - Spring Boot - 不使用 WebSecurityConfigurerAdapter 的自定义身份验证过滤器

java - 如何防止为某些类创建 java-doc

java - 如何运行 java 程序并查看使用了哪些方法/类来生成输出?

java - Class.getFields() 返回的字段顺序

java - 通过反射获取String变量的值

c# - 类型反射中的重复项目(?)

用于注释文本的 Javascript 库?

spring - Spring 3.0中@Value注解的不方便

ios - 图钉未显示在 map View 中。 swift 5