Is there any technique available in Java for intercepting messages (method calls) like the method_missing technique in Ruby? This would allow coding decorators and proxies very
easily, like in Ruby:
:Client p:Proxy im:Implementation
------- ---------- -----------------
p.foo() -------> method_missing()
do_something
im.foo() ------------------> do_foo
p.bar() --------> method_missing()
do_something_more
im.bar() -------------------> do_bar
(Note: Proxy only has one method: method_missing())
As others have correctly said already, use a DynamicProxy. Here’s an example.
This class uses a DynamicProxy to intercept invocations of methods declared in the “HammerListener” interface. It does some logging and then delegates to the “real” HammerListener implementation (yes, the same thing can be done with AOP).
See the newInstance method for proxy instantiation (note that you need to pass in the interface(s) the proxy should implement – a proxy can implement multiple interface).
All method invocations on interfaces that the proxy implements will end up as calls to the “invoke” method, which is declared in the “InvocationHandler” interface. All proxy handlers must implement this interface.