如何使用反射获取注解类名、属性值 [英] How to get annotation class name, attribute values using reflection
问题描述
我知道如果我们知道注解类,我们可以很容易地得到具体的注解并访问它的属性.例如:
I know if we know the annotation class, we can easily get the specific annotation and access its attribute. For example:
field.getAnnotation(Class<T> annotationClass)
这将返回特定注释接口的引用,因此您可以轻松访问其值.
Which will return a reference of specific annotation interface, so you can easily access its values.
我的问题是我是否对特定的注释类没有预先了解.我只想使用反射在运行时获取所有注释类名称及其属性,以便将类信息转储为 JSON 文件.我怎样才能以简单的方式做到这一点.
My question is if I have no pre knowledge about the particular annotations class. I just want to use reflection to get all the annotation class name and their attributes at run-time for the purpose of dumping the class information for example as a JSON file. How can I do it in an easy way.
Annotation[] field.getAnnotations();
这个方法只会返回注解接口的动态代理.
This method will only return dynamic proxies of the annotation interfaces.
推荐答案
与人们的预期相反,注解的元素不是属性 - 它们实际上是返回提供值或默认值的方法.
Contrary to what one might expect, the elements of an annotation are not attributes - they are actually methods that return the provided value or a default value.
您必须遍历注释的方法并调用它们以获取值.使用annotationType()
获取注解的类,getClass()
返回的对象只是一个代理.
You have to iterate through the annotations' methods and invoke them to get the values. Use annotationType()
to get the annotation's class, the object returned by getClass()
is just a proxy.
这是一个打印 @Resource
一个类的注解:
Here is an example which prints all elements and their values of the @Resource
annotation of a class:
@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
避免警告的论据.
Thanks to Aaron for pointing out the you need to cast the null
argument to avoid warnings.
这篇关于如何使用反射获取注解类名、属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!