Loading

【IllegalArgumentException】: object is not an instance of declaring class

java.lang.IllegalArgumentException: object is not an instance of declaring class

日前在调试动态代理的例子中,出现以上报错,关键代码如下:

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    System.out.println("执行" + method.getName());


    if (method.getName().equals("writeFile")){

        Method method1 = proxy.getClass().getMethod("fetchData");
        Method method2 = proxy.getClass().getMethod("makeContent", Object.class);
        List<Object> dataList = (List<Object>) method1.invoke(proxy);

        try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("D:/Test/test/123.txt"))){
            for (Object o : dataList) {
                String oneInfo = (String) method2.invoke(obj,o);
                bufferedWriter.write(oneInfo);
            }
        }
        return null;

    }else {
        return method.invoke(obj,args);
    }
}

第15行
String oneInfo = (String) method2.invoke(obj,o);
应改为
String oneInfo = (String) method2.invoke(proxy,o);
为何会这样?我们先来了解一下invoke()方法:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {}
官方JDK是这样解释的:

A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance,a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to the invoke method of the instance's invocation handler, passing the proxy instance,a java.lang.reflect.Method object identifying the method that was invoked, and an array of type Object containing the arguments.
通过一个代理接口对代理实例的方法调用将被分派到实例调用处理程序的调用方法,传递代理实例、标识被调用方法的java.lang.reflect.Method对象和一个包含参数的object类型数组。

  • Object proxy:代理实例
  • Method method:被调用的方法
  • Object[] args:被调用方法的参数

我们可以看到,与22行的区别是代理实例的不同,而代理是实例的不同是因为调用方法的不同,method1方法是通过代理实例proxy获得,所以它必须传入代理实例proxy,而method方法代理的是该类的一个变量obj,更深入的了解后续探讨。

posted @ 2021-07-08 13:58  Acelin_H  阅读(1702)  评论(0编辑  收藏  举报