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?
It is because, while from your test code you are calling
proxy.a()
, your finala()
method is not callingproxy.b()
, but straight to the self instanceb()
.As a workaround, you can overload every method passing it a delegate instance. Suposing a class name of MyClass and a interface name of MyInterface:
Then, from your test code you'll be able to call
proxy.a(proxy)
, and get the expected result.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.