如何使用反射获取注释类名,属性值

Jia*_*hen 33 java reflection annotations

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

field.getAnnotation(Class<T> annotationClass) 
Run Code Online (Sandbox Code Playgroud)

这将返回特定注释界面的引用,因此您可以轻松访问它的值.

我的问题是,如果我对特定的注释类没有预先知识.我只想在运行时使用反射来获取所有注释类名及其属性,以便将类信息转储为例如json文件.我怎么能以简单的方式做到这一点.

Annotation[] field.getAnnotations();
Run Code Online (Sandbox Code Playgroud)

此方法仅返回注释接口的动态代理.

kap*_*pex 70

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

您必须遍历注释的方法并调用它们来获取值.使用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);
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Values of javax.annotation.Resource
 name: foo
 type: class java.lang.Object
 lookup: 
 description: bar
 authenticationType: CONTAINER
 mappedName: 
 shareable: true
Run Code Online (Sandbox Code Playgroud)

感谢Aaron指出你需要施放null论据以避免警告.


Aar*_*ron 13

只是为了跟进上面的答案(我没有足够的代表回复它):

method.invoke(annotation, null)
Run Code Online (Sandbox Code Playgroud)

应该更改为以下内容,否则会抛出异常:

method.invoke(annotation, (Object[])null) or method.invoke(annotation, new Object[0])
Run Code Online (Sandbox Code Playgroud)