有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我正在使用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());

但到目前为止,我还不能这样做,使用反射。。。我将非常感谢任何指示,提前谢谢。 注:是否有任何方法可以获取参数对象,如字段对字段、方法对方法等


共 (1) 个答案

  1. # 1 楼答案

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

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