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:
Invoke the proxy by:
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).