[英]What object do I pass when invoking a method using reflection
I am using Reflections to obtain a method from a class that is annotated with a specific annotation. 我正在使用Reflection从一个使用特定注释注释的类中获取方法。 Once I get the list of methods in the class, I loop through the methods and if the method matches a specific return type, I want to invoke that method.
一旦我获得了类中的方法列表,我循环遍历方法,如果方法匹配特定的返回类型,我想调用该方法。 For testing purposes I know that the method I am getting returns a String.
出于测试目的,我知道我得到的方法返回一个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));
}
}
}
}
This is the method I am attempting to invoke 这是我试图调用的方法
@DependantResource
public String showInjector() {
return "This is an injector";
}
I keep getting the following error and I know it has everything to do with the object I am passing into invoke, but is the method from the loop not the object I am supposed to be passing? 我一直得到以下错误,我知道它与我传递给调用的对象有关,但是循环中的方法不是我应该传递的对象吗?
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)
This is not correct: 这不正确:
method.invoke(method,(Object[]) null)
You should instantiate an object first, and then make a call. 您应该首先实例化一个对象,然后进行调用。 Something like:
就像是:
method.invoke(clazz.newInstance(), (Object[]) null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.