2 napoleonjk napoleonjk 于 2014.05.16 16:53 提问

java动态代理测试报错

今天突然看到spring aop,想到代理模式,就写了个动态代理的例子,但是有点不遂人愿,出错了,各位大牛帮我看下哪里错了.

程序里头可能是有死循环或递归调用所产生的?增大JVM的内存?

public interface Subject {

void opration();

}

public class RealSubject implements Subject {

@Override
public void opration() {
    System.out.println("I am a RealSubject");

}

}

public class ProxyInvocationHandler implements InvocationHandler {

private Object beProxy;

public ProxyInvocationHandler(Object beProxy) {
    super();
    this.beProxy = beProxy;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    System.out.println("proxy class:" + proxy + "proxy method:" + method);

    return method.invoke(beProxy, args);
}

}

public class TestDynamicProxy {

public static void main(String[] args) {
    Subject proxyClass = (Subject) Proxy.newProxyInstance(Subject.class.getClassLoader(),
            new Class[] { Subject.class }, 
            new ProxyInvocationHandler(new RealSubject()));
    proxyClass.opration();

}

}

Exception in thread "main" java.lang.StackOverflowError
at java.lang.AbstractStringBuilder.(AbstractStringBuilder.java:44)
at java.lang.StringBuilder.(StringBuilder.java:92)
at com.test.dynamic.proxy.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:32)
at com.sun.proxy.$Proxy0.toString(Unknown Source)
at java.lang.String.valueOf(String.java:2826)
at java.lang.StringBuilder.append(StringBuilder.java:115)
at com.test.dynamic.proxy.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:32)
at com.sun.proxy.$Proxy0.toString(Unknown Source)
at java.lang.String.valueOf(String.java:2826)
at java.lang.StringBuilder.append(StringBuilder.java:115)
at com.test.dynamic.proxy.ProxyInvocationHandler.invoke(ProxyInvocationHandler.java:32)
at com.sun.proxy.$Proxy0.toString(Unknown Source)
at java.lang.String.valueOf(String.java:2826)
at java.lang.StringBuilder.append(StringBuilder.java:115)

3个回答

lymoge
lymoge   2014.05.16 17:45

proxy.toString()递归调用InvocationHandler的invoke方法,导致堆栈溢出。搜一下$Proxy0的源码就知道。

napoleonjk
napoleonjk 恩,这样就ok了。System.out.println("proxy class:" + proxy.getClass() + "\nproxy method:" + method.getName());
3 年多之前 回复
gl4532
gl4532   2015.06.02 15:08

怎么解决呢 他并没有调用toString()方法呀

napoleonjk
napoleonjk System.out.println("proxy class:" + proxy.getClass() + "\nproxy method:" + method.getName());
2 年多之前 回复
napoleonjk
napoleonjk System.out.println("proxy class:" + proxy + "proxy method:" + method);
2 年多之前 回复
napoleonjk
napoleonjk System.out.println("proxy class:" + proxy + "proxy method:" + method);
2 年多之前 回复
Aronren
Aronren   2016.03.28 17:03

字符串连接符号 +, 自动调用toString()

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!