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屋!