Java proxy example creates stack overflow?

I am collecting some snippets and sample code to reflect Java. Here is my naive sample code for using proxies:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

interface MyInterface { void foo(); }

class Handler implements InvocationHandler {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("Called for : " + proxy);
    System.out.println("Called with: " + method);
    return null;
    }
}

public class ProxyExample {
    public static void main(String args[]) {
    Handler handler = new Handler();
    MyInterface proxied = (MyInterface) Proxy.newProxyInstance(MyInterface.class.getClassLoader(),
            new Class[] { MyInterface.class }, handler);
    proxied.foo();
    }
}

Can you guess what will happen?

Exception in thread "main" java.lang.StackOverflowError
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:422)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at java.lang.StringBuilder.<init>(StringBuilder.java:113)
at xxx..Handler.invoke(ProxyExample.java:15)

When I comment on the first listing, I get:

Called with: public abstract void xxx.MyInterface.foo()

Any idea what causes stack overflow and overflow?

+4
source share
1 answer

System.out.println("Called for : " + proxy);

Call the proxy method toString(), call the handler again, causing infinite recursion.

+4
source

All Articles