如何获取一个类及其超类的注释列表 [英] How to get the list of annotations of a class and its superclass
问题描述
我正在编写一种方法,用于检索声明类及其超类的特定方法的所有注释.
I'm writing a method supposed to retrieve all annotations of a specific method declaring class and its superclasses.
通过在声明类上使用方法 getAnnotations()
,结果表仅包含声明类注释,而超类注释将被忽略.如果我删除声明类的注释,那么将存在超类注释.
By using the method getAnnotations()
on the declaring class, the resulting table contains only the declaring class annotations and the superclass annotations are ignored.
If I remove the annotations of the declaring class, then the superclass annotation are present.
我在这里想念什么?
检索注释的简化方法:
public void check(Method invokedMethod) {
for (Annotation annotation : invokedMethod.getDeclaringClass().getAnnotations()) {
// Do something ...
}
}
(我尝试获取的所有注释都具有 @Inherited
注释)
(All annotations I'm trying the get have the @Inherited
annotation)
推荐答案
如果您需要处理多个相同类型的注释,则标准方法无效,因为注释存储在 Map 注释类型为键的code>.(请参阅更多
In case you need to process several annotations of the same type, the standard approach is does not work, because annotations are stored in a Map
with annotation types as the key. (See more here). Here is how I would work around this problem (just go through all super classes manually):
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
public class AnnotationReflectionTest {
public static void main(String[] args) throws Exception {
check(Class2.class.getMethod("num", new Class[0]));
}
public static void check(Method invokedMethod) {
Class<?> type = invokedMethod.getDeclaringClass();
while (type != null) {
for (Annotation annotation : type.getDeclaredAnnotations()) {
System.out.println(annotation.toString());
}
type = type.getSuperclass();
}
}
}
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Annot1 {
int num();
}
@Annot1(num = 5)
class Class1 {
public int num() {
return 1;
}
}
@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Annot2 {
String text();
}
@Annot2(text = "ttt")
class Class2 extends Class1 {
public int num() {
return super.num() + 1;
}
}
您使用什么版本的Java和什么操作系统?
What version of Java and what OS do you use?
这篇关于如何获取一个类及其超类的注释列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!