java.lang.IllegalArgumentException: object is not an instance of declaring classjava
日前在调试动态代理的例子中,出现以上报错,关键代码以下:数组
@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是这样解释的:ide
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类型数组。fetch
咱们能够看到,与22行的区别是代理实例的不一样,而代理是实例的不一样是由于调用方法的不一样,method1方法是经过代理实例proxy得到,因此它必须传入代理实例proxy,而method方法代理的是该类的一个变量obj,更深刻的了解后续探讨。spa