gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:55:35 28 4
gpt4 key购买 nike

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

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com