I am putting together some foils and example code on Java reflection. Here is my naive example 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 out the first printout, I get:
Called with: public abstract void xxx.MyInterface.foo()
Any idea what is causing the recursion and stack overflow?
Aucun commentaire:
Enregistrer un commentaire