【问题标题】:IllegalArgumentException when passing in a class which implements an interface in java reflect传入在java中实现接口的类时出现IllegalArgumentException反射
【发布时间】:2017-01-23 07:38:45
【问题描述】:

我有一门课叫

ServiceImpl 

实现接口

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,为什么这会是个问题呢?我该如何解决这个问题?

【问题讨论】:

    标签: java class reflection interface


    【解决方案1】:

    反射抱怨的不是Service参数,而是第一个参数。实际上,您的代码会尝试这样做:

    "setService".setService(myService);
    

    由于显而易见的原因,这不起作用。

    将要设置服务的对象作为第一个参数传递来解决此问题:

    method.invoke(instanceOfBeanClass, myService);
    

    【讨论】:

    • 我应该想到显示这样的有效调用,很好。
    【解决方案2】:

    您正试图在字符串对象"setService" 上调用setServiceMethod#invoke的第一个参数是调用方法的对象,而不是方法的名称(它已经知道是谁了)。

    你想要的:

    method.invoke(bean, myService);
    

    ...其中beanClass 对象beanClass 所引用的类的一个实例。

    【讨论】:

      猜你喜欢
      • 2013-10-26
      • 2013-01-18
      • 2023-03-03
      • 1970-01-01
      • 2010-09-09
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2015-10-21
      相关资源
      最近更新 更多