public class BeproxyPerson {
public void say(){
System.out.println("be_say");
}
}
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ProxyPerson implements MethodInterceptor {
private BeproxyPerson beproxyPerson ;
public ProxyPerson(BeproxyPerson beproxyPerson) {
this.beproxyPerson = beproxyPerson;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before method run...");
System.out.println(o.toString());
System.out.println(method.getName());
System.out.println(Arrays.toString(objects));
System.out.println(methodProxy.getSuperName());
Object result = methodProxy.invokeSuper(o, objects);
System.out.println("after method run...");
return result;
}
}
import org.junit.Test;
import org.springframework.cglib.proxy.Enhancer;
public class testProxyPerson {
@Test
public void t1() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(BeproxyPerson.class);
enhancer.setCallback(new ProxyPerson(new BeproxyPerson()));
((BeproxyPerson) enhancer.create()).say();
}
}
是这一行代码导致的
System.out.println(o.toString());
测试jdk 动态代理,也会出现这种现像
查看动态生成的第三代理类tostring的方法
return (String)super.h.invoke(this, m2, (Object[])null);
实际是又一次调用invoke,试图找到对tostring的增强。于是形成死循环
类似的hashcode方法
return (Integer)super.h.invoke(this, m0, (Object[])null);
也会导致死循环,其他方法就不赘述了