![](/img/trans.png)
[英]Why do I get “object is not an instance of declaring class” when invoking a method using reflection?
[英]What object do I pass when invoking a method using reflection
我正在使用Reflection从一个使用特定注释注释的类中获取方法。 一旦我获得了类中的方法列表,我循环遍历方法,如果方法匹配特定的返回类型,我想调用该方法。 出于测试目的,我知道我得到的方法返回一个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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.