java.lang.IllegalArgumentException: object is not an instance of declaring class
In the example of debugging dynamic proxy a few days ago, the above error occurred. The key code is as follows:
@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);
}
}
Line 15
String oneInfo = (String) method2.invoke(obj,o);
should be changed to
String oneInfo = (String) method2.invoke(proxy,o);
Why does this happen? Let’s first understand the invoke() method: the
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {}
official JDK explains it like this:
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.
A method call to a proxy instance through a proxy interface will be dispatched to the calling method of the instance call handler, passing the proxy instance and identifying the java.lang.reflect of the called method .Method object and an array of object type containing parameters.
- Object proxy: proxy instance
- Method method: the method to be called
- Object[] args: the parameters of the called method
We can see that the difference from line 22 is that the proxy instance is different, and the proxy is the instance is different because of the different calling methods. The method1 method is obtained through the proxy instance proxy, so it must be passed into the proxy instance proxy, and the method method The agent is a variable obj of this class, for a more in-depth understanding of the follow-up discussion.