0

here is the method signature from the Proxy class:

Object java.lang.reflect.Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException

I check the source code of the newProxyInstance in the Proxy Class, i couldn't find where the proxy object pass itself to the InvocationHandler method

public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;

Does anyone know?

Thanks

stevevls
  • 10,675
  • 1
  • 45
  • 50
skystar7
  • 4,419
  • 11
  • 38
  • 41

1 Answers1

8

You're on the hook to provide the reference through the usual means. One common pattern is to create a final variable to reference the target and pass an anonymous implementation of InvocationTargetHandler to the Proxy.newProxyInstance method like so:

final Object myObject = /*initialize the proxy target*/;
final Object proxy = Proxy.newProxyInstance(
    classLoader,
    new Class[] { /*your interface(s)*/ }, 
    new InvocationTargetHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) {
            return method.invoke(myObject, args);
        }
});

This example is the most pointless proxy in the world because it patches all method calls through without doing anything, but you can fill in the InvocationTargetHandler with all sorts of fun stuff.

Sometimes the API feels a little bit klunky because the proxied object doesn't form part of the contract, but the JDK authors wanted to provide the possibility for the proxy class to exist without a backing concrete implementation. It's quite useful that they did it that way...mock objects in your unit tests are a great of example.

stevevls
  • 10,675
  • 1
  • 45
  • 50
  • Thank you so much for your reply, my question not how to pass a proxy obj to the InvocationTargetHandler, my question is how the proxy got passed in the design? hence when i call proxy.getClass().getName() from invoke method, i got the same instance class name of my proxy. – skystar7 Dec 04 '12 at 21:36
  • 1
    @skystar7 no problem! so if i understand correctly now, you're asking about the byte-code that the JRE generates when you call `newProxyInstance`. if you delve into the JRE code, you'll find a class called `sun.misc.ProxyGenerator`. that guy generates byte code for each proxy class that creates stub methods to invoke your proxy handler. within those stub methods, the `proxy` parameter is simply passed as `this`. – stevevls Dec 04 '12 at 22:31