如何获取类及其超类的注释列表 [英] 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
以注释类型为键.(查看更多 此处).以下是我将如何解决此问题(只需手动检查所有超类):
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屋!