gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:02:11 30 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/20362493/

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