JAVA-如何从注释中获取注释? [英] JAVA - How to get annotations from Annotation?
问题描述
我想从注释中获取注释,但是奇怪的是我无法从注释实例中获取单个注释.我该如何解决?我想从此注释实例中获取注释.
I want to get annotations from annotation, but the weird thing is I can't get single annotation from annotation instance. How do I solve this? I want to get annotations from this annotation instance.
public static void test(Annotation annotation) {
System.out.println("ValidBoolean annotation len:" + ValidBoolean.class.getAnnotations().length);
System.out.println(annotation.getClass().getName() + ":" + annotation.getClass().getAnnotations().length);
if (annotation instanceof ValidBoolean) {
ValidBoolean validBoolean = (ValidBoolean) annotation;
System.out.println("[BOOLEAN]" + validBoolean.getClass().getName() + ":" + validBoolean.getClass().getAnnotations().length);
}
}
打印结果是:
ValidBoolean annotation len:3
com.sun.proxy.$Proxy28:0
[BOOLEAN]com.sun.proxy.$Proxy28:0
推荐答案
如果我对您的理解正确,那么您想这样做:
If I understand you correctly, you want to do:
Annotation[] annotationAnnotations = annotation.annotationType().getAnnotations();
通常, annotationType()
如此工作
Generally, annotationType()
works such that
someClass.getAnnotation(someAnnotationClass).annotationType() == someAnnotationClass
所以annotation instanceof ValidBoolean
也暗示annotation.annotationType() == ValidBoolean.class
,因此在它们上调用.getAnnotations()
将导致相同的注释.
So annotation instanceof ValidBoolean
also implies annotation.annotationType() == ValidBoolean.class
, thus invoking .getAnnotations()
on them will lead to the same annotations.
这篇关于JAVA-如何从注释中获取注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!