2

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

do you mean using a proxied obj instead of the obj inside the invocation handler? i tried instead to let the invocation handler extends my object's class and apply the invoke method on the same invochandler instance ( method.invoke(this, args), i thought it would pretend to be the object but having each method call filtered by the proxy ), but once again it fails.
2

It is because, while from your test code you are calling proxy.a(), your final a() method is not calling proxy.b(), but straight to the self instance b() .

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:

void a() { //to keep the non-proxy working, the default method have to pass the //self intance a(this); } void a(MyInterface target) { target.b(target); } void b() { b(this); } void b(MyInterface target) { target.c(target); } void c() { c(this); } void c(MyInterface target) { //do whatever } 

Then, from your test code you'll be able to call proxy.a(proxy), and get the expected result.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.