I read the sample about proxy here:
http://docs.oracle.com/javase/1.3/docs/guide/reflection/proxy.html
As you can see, the parameter ‘proxy’ in the method of ‘invoke’ is not used. What is the proxy used for? Why not use it here: result = m.invoke(proxy, args); ?
public class DebugProxy implements java.lang.reflect.InvocationHandler {
private Object obj;
public static Object newInstance(Object obj) {
return java.lang.reflect.Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
new DebugProxy(obj));
}
private DebugProxy(Object obj) {
this.obj = obj;
}
public Object invoke(Object proxy, Method m, Object[] args)
throws Throwable
{
Object result;
try {
System.out.println("before method " + m.getName());
result = m.invoke(obj, args);
} catch (InvocationTargetException e) {
throw e.getTargetException();
} catch (Exception e) {
throw new RuntimeException("unexpected invocation exception: " +
e.getMessage());
} finally {
System.out.println("after method " + m.getName());
}
return result;
}
}
proxy is specially constructed by JVM “dynamic proxy” class. Your code can’t invoke directly it’s method. Alternative way to think about this is that proxy is “interface”, invoking any method on it correspond to invoking
public Object invoke(Object proxy, Method m, Object[] args)method, so invoking method on proxy will end with infinite loop.