今天在用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;
}
}