1

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;
}

}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. Why we have the parameter since we can not use it. Why not hidden it?
Why to hide if it takes no cost to show. :-) Maybe you want to introspect this class (for example, to call getClass() method).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.