Java Dynamic Proxy - as a reference specific class

I have a question related to dynamic proxies in java.

Suppose I have an interface named Foo with the execute method 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 call handler looks like this:

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

If my call code looks something like this:

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

If the proxy can intercept the above call to execute from the Foo interface, which includes FooImpl , to play? Maybe I'm looking at dynamic proxies the wrong way. I want to catch the execute call from a specific implementation of Foo , for example FooImpl . It can be done?

Many thanks

+5
java dynamic proxy
source share
2 answers

Method interception using dynamic proxies:

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

Call proxy:

 Foo foo = (Foo) Proxy.newProxyInstance( Foo.class.getClassLoader(), new Class[] {Foo.class}, new FooHandler(new FooImpl())); 
+3
source share

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

+2
source share

All Articles