I have a class called
ServiceImpl
which implents the interface
Service
I have a method in another jar which I want to call but it takes
Service
as input. Here is the method:
public void setService(Service service) {
context.setService(service);
}
I tried to use reflection to call this method
final ServiceImpl myService = new ServiceImpl(param1, param2);
method = beanClass.getMethod("setService",Service.class);
method.invoke("setService", myService);
However I get the error:
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
It is saying that it expects a Service class but I am passing in an object of type ServiceImpl. But why should that be a problem, since ServiceImpl has implemented Service? How can I work around this?
You're trying to call setService on a string object, "setService". Method#invoke's first parameter is the object to call the method on, not the name of the method (it already knows who it is).
You wanted:
method.invoke(bean, myService);
...where bean is an instance of the class whose Class object beanClass refers to.
It is not the Service parameter that the reflection is complaining about, it is the first parameter. Effectively, your code attempts to do this:
"setService".setService(myService);
which does not work for obvious reasons.
Pass the object on which you want to set the service as the first parameter to fix this problem:
method.invoke(instanceOfBeanClass, myService);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With