javaproxynestedinvocationhandler

Dynamic Proxy: how to handle nested method calls


I'm trying to learn Dynamic Proxies in Java.

I know how they work but I can't find a solution to my problem: given an interface and its implementation with methods a(), b() and c() nested one into the other (let's say a() calls b() which calls c()), I would like to proxy my object to log EACH call to the methods.

So I code my InvocationHandler such as the invoke() method prints a log-line before the execution.

But when I call proxy.a(), only the call of method a() is logged and not the whole chain of methods.

What am I missing? Is the target of the proxy have to be a proxy itself?


Solution

  • Well, the object itself doesn't know that it is being proxied, so when a() calls b(), it will be a normal "intra object" call.

    If the target of the proxy is the proxy itself, you will have a loop.

    One way to solve this, if it's really needed, would be to introduce a delegate to the target object and set it up with the proxy or with itself as delegate. Strange, but might work. Look out for loops, though.