Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Dynamic Proxy - How reference concrete class

I have a question relating to dynamic proxies in java.

Suppose I have an interface called Foo with a method execute and class FooImpl implements Foo.

When I create a proxy for Foo and I have something like:

Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
                                     new Class[] { Foo.class },
                                     handler);

Suppose my invocation handler looks like:

public class FooHandler implements InvocationHandler {
    public Object invoke(Object proxy, Method method, Object[] args) {
        ...
    }
}

If my invocation code looks something like

Foo proxyFoo = (Foo) Proxy.newInstance(Foo.getClass().getClassLoader(),
                                       new Class[] { Foo.class },
                                       new FooHandler());
proxyFoo.execute();

If the proxy can intercept the aforementioned call execute from the Foo interface, where does the FooImpl come in to play? Maybe I am looking at dynamic proxies in the wrong way. What I want is to be able to catch the execute call from a concrete implementation of Foo, such as FooImpl. Can this be done?

Many thanks

like image 930
Joeblackdev Avatar asked Mar 02 '11 12:03

Joeblackdev


2 Answers

The way to intercept methods using dynamic proxies are by:

public class FooHandler implements InvocationHandler {
    private Object realObject;

    public FooHandler (Object real) {
        realObject=real;
    }


    public Object invoke(Object target, Method method, Object[] arguments) throws Throwable {
        if ("execute".equals(method.getName()) {
            // intercept method named "execute"
        }

        // invoke the original methods
        return method.invoke(realObject, arguments);
    }
}

Invoke the proxy by:

Foo foo = (Foo) Proxy.newProxyInstance(
            Foo.class.getClassLoader(),
            new Class[] {Foo.class}, 
            new FooHandler(new FooImpl()));
like image 147
Johan Sjöberg Avatar answered Sep 23 '22 17:09

Johan Sjöberg


If you want to delegate to some Foo implementation like FooImpl, just make your InvocationHandler a wrapper of an other Foo instance (passed to the constructor) and then send a FooImpl instance as the delegate. Then, inside the handler.invoke() method, call method.invoke(delegate, args).

like image 34
Costi Ciudatu Avatar answered Sep 26 '22 17:09

Costi Ciudatu