Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IllegalArgumentException when passing in a class which implements an interface in java reflect

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?

like image 239
user3809938 Avatar asked Mar 02 '26 00:03

user3809938


2 Answers

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.

like image 65
T.J. Crowder Avatar answered Mar 03 '26 13:03

T.J. Crowder


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);
like image 45
Sergey Kalinichenko Avatar answered Mar 03 '26 14:03

Sergey Kalinichenko