gpt4 book ai didi

java - 获取java中方法或构造函数参数上注释的对象

转载 作者:太空宇宙 更新时间:2023-11-04 08:15:30 24 4
gpt4 key购买 nike

我正在使用 Scannotation 扫描类文件并获取该类的任何元素上存在注释的所有类。使用反射,我已经能够找到方法中参数的所有注释,但我需要这些注释的对象,以便以后可以获取其参数(或者你怎么调用它)。

这是我的代码的一部分,它将返回我想要的注释,但我无法使用它们。

    public Set<Class> getParametersAnnotatedBy(Class<? extends Annotation> annotation) {
for (String s : annotated) {
//annotated is set containing names of annotated classes
clazz = Class.forName(s);
for (Method m : clazz.getDeclaredMethods()) {
int i = 0;
Class[] params = m.getParameterTypes();
for (Annotation[] ann : m.getParameterAnnotations()) {
for (Annotation a : ann) {
if (annotation.getClass().isInstance(a.getClass())) {
parameters.add(a.getClass());
//here i add annotation to a set
}
}
}
}
}
}

如果我知道注释,我知道我可以使用它,如下所示:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
public String name();
public int count();
}
// ... some code to get annotations
MyAnnotation ann = (MyAnnotation) someAnnotation;
System.out.println(ann.name());
System.out.println(ann.count());

但到目前为止,我还无法使用反射来做到这一点...我非常感谢任何指示,提前致谢。PS.:有什么方法可以获取参数对象,例如字段的 Field、方法的 Method 等?

最佳答案

您需要使用a.annotationType。当您在注释上调用 getClass 时,您实际上得到的是它的 Proxy Class 。要获取真正的类,您需要调用 annotationType 而不是 getClass

if (annotation.getClass() == a.annotationType()) {
parameters.add(a.annotationType());
// here i add annotation to a set
}

关于java - 获取java中方法或构造函数参数上注释的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10503877/

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