Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top