与预期的相反,注释的元素不是属性-它们实际上是返回提供的值或默认值的方法。
您必须遍历注释的方法并调用它们以获取值。使用
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
参数以避免警告。



