今天在用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;
}
}
本文探讨了使用Java反射实现方法拦截时遇到的递归死循环问题,详细分析了问题根源在于代理对象在invoke方法中无限调用自身,最终导致栈溢出错误。
1万+

被折叠的 条评论
为什么被折叠?



