我有一个类叫
ServiceImpl
实现接口(interface)
Service
我在另一个 jar 中有一个方法,我想调用它,但它需要
Service
作为输入。方法如下:
public void setService(Service service) {
context.setService(service);
}
我试过用反射来调用这个方法
final ServiceImpl myService = new ServiceImpl(param1, param2);
method = beanClass.getMethod("setService",Service.class);
method.invoke("setService", myService);
但是我得到了错误:
Exception in thread "main" java.lang.IllegalArgumentException: object is not an instance of declaring class
它说它需要一个服务类,但我传入了一个 ServiceImpl 类型的对象。但既然 ServiceImpl 已经实现了 Service,那为什么会成为问题呢?我该如何解决这个问题?
最佳答案
您正在尝试对字符串对象"setService"
调用setService
。 Method#invoke
的第一个参数是调用方法的对象,而不是方法的名称(它已经知道它是谁了)。
你想要:
method.invoke(bean, myService);
...其中 bean
是其 Class
对象 beanClass
引用的类的实例。
关于java - 传入在 java 中实现接口(interface)的类时出现 IllegalArgumentException 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39508376/