如何获得注释的类名,属性使用反射值 [英] 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 it's attribute. For example:
field.getAnnotation(Class<T> annotationClass)
这将返回特定注释界面的参考,让您可以轻松地访问它的值。
Which will return a reference of specific annotation interface, so you can easily access it's values.
我的问题是,如果我有关于特定注释类中没有pre知识。我只是想使用反射来获取所有标注类的名称,并在运行时倾倒例如,作为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 json file. How can I do it in a easy way.
Annotation[] field.getAnnotations();
这个方法将只返回注释接口的动态代理。
This method will only return dynamic proxies of the annotation interfaces.
推荐答案
您必须通过注释的方法进行迭代并调用他们得到的值。使用 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(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
的感谢亚伦指出的的,你需要投的空
参数,以避免警告。的
Thanks to Aaron for pointing out the you need to cast the null
argument to avoid warnings.
这篇关于如何获得注释的类名,属性使用反射值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!