Dynamic Proxy: how to handle nested method calls

2019-06-10 19:27发布

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条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-10 19:38

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-06-10 19:47

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.

查看更多
登录 后发表回答