Java Dynamic Proxy - How reference concrete class

2019-03-30 06:01发布

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

2条回答
Lonely孤独者°
2楼-- · 2019-03-30 06:57

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()));
查看更多
爷、活的狠高调
3楼-- · 2019-03-30 06:57

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

查看更多
登录 后发表回答