【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 @   Acelin_H  阅读(2142)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
主题色彩
点击右上角即可分享
微信分享提示