gpt4 book ai didi

java - 如何获取类及其父类(super class)的注释列表

转载 作者:行者123 更新时间:2023-11-30 10:57:44 35 4
gpt4 key购买 nike

我正在编写一个方法来检索声明类及其父类(super class)的特定方法的所有注释。

通过在声明类上使用方法 getAnnotations(),生成的表仅包含声明类注释,而忽略父类(super class)注释。如果我删除声明类的注释,那么父类(super class)注释就会存在。

我在这里错过了什么?

检索注释的简化方法:

public void check(Method invokedMethod) {
for (Annotation annotation : invokedMethod.getDeclaringClass().getAnnotations()) {
// Do something ...
}
}

(我尝试获取的所有注释都具有 @Inherited 注释)

最佳答案

如果您需要处理多个相同类型的注解,标准方法是行不通的,因为注解存储在以注解类型为键的 Map 中。 (查看更多 here )。以下是我将如何解决这个问题(只需手动遍历所有父类(super class)):

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 和什么操作系统?

关于java - 如何获取类及其父类(super class)的注释列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32467494/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com