简体   繁体   中英

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

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()));

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM