问题描述
在实现动态代理时发现,运行时会不断循环执行InvocationHandler中的的invoce方法,导致内存溢出
// cls是一个类
Strategy strategy = (Strategy) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// ...
// 注意method.invoke()方法的传参
return method.invoke(proxy,args);
}
}
原因分析
排查原因,发现是在invoke内部没有使用被代理的对象,而是使用了方法中传入的Object参数(即,proxy)。
解决方法
// cls是一个类
Strategy strategy = (Strategy) Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// ...
// 注意method.invoke()方法的传参
return method.invoke(cls, args);
}
}