I am using Reflections to obtain a method from a class that is annotated with a specific annotation. 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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.