method.invoke导致递归死循环,at com.sun.proxy.$Proxy0.add(Unknown Source)

 今天在用java反射实现方法拦截的时候出现递归死循环的问题,报错信息如下

对比源代码,差别如下,在这个invoke方法里面,proxy会再次调用这个invoke方法,无限循环,导致栈溢出。

视频链接:https://www.youtube.com/watch?v=8zt_HftX-4g

 

@Slf4j
public class ArithmeticCalculateProxy {
    private ArithmeticCalculate target;
    public ArithmeticCalculateProxy(ArithmeticCalculate target){
        this.target = target;
    }
    public ArithmeticCalculate getLogProxy() throws Exception{
        ArithmeticCalculate proxy = null;

        //代理对象由哪一个类加载器负责加载
        ClassLoader loader = target.getClass().getClassLoader();

        //代理对象的类型,获取其中的方法
        Class[] classes = new Class[]{ArithmeticCalculate.class};

        //当调用代理对象其中的方法时,该执行的代码
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String methodName = method.getName();
                //日志
                log.info("method name is {}, params is {}", methodName, Arrays.asList(args));
                //方法
                Object ret = method.invoke(proxy, args);
                //日志
                log.info("method name is {}, return value is {}", methodName, ret);
                return 0;
            }
        };
        proxy = (ArithmeticCalculate) Proxy.newProxyInstance(loader, classes, invocationHandler);
        return proxy;
    }
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值