jeudi 15 septembre 2016

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?





Aucun commentaire:

Enregistrer un commentaire