我正在使用Reflections从带有特定批注的类中获取方法。一旦获得了类中的方法列表,便会遍历这些方法,如果该方法与特定的返回类型匹配,则我想调用该方法。出于测试目的,我知道我要获取的方法返回一个String。

Reflections reflections = new Reflections(new ConfigurationBuilder()
        .setScanners(new TypesScanner(), new TypeElementsScanner())
        .setUrls(ClasspathHelper.forPackage("stressball"))
);

Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(DependantClass.class);
System.out.println(annotated);

for(Class<?> clazz : annotated) {
    for(Method method : clazz.getMethods()) {
        if(method.isAnnotationPresent(DependantResource.class)) {
            if(method.getReturnType() == String.class) {
                System.out.println(method.invoke(method,(Object[]) null));
            }
        }
    }
}

这是我尝试调用的方法
@DependantResource
public String showInjector() {
    return "This is an injector";
}

我不断收到以下错误,我知道它与我传递给调用的对象有关,但是循环中的方法不是我应该传递的对象吗?
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at stressball.test.DefaultTest.main(DefaultTest.java:35)

最佳答案

这是不正确的:

method.invoke(method,(Object[]) null)

您应该首先实例化一个对象,然后进行调用。就像是:
method.invoke(clazz.newInstance(), (Object[]) null)

09-09 23:45
查看更多