动态代理:如何处理嵌套方法调用 [英] Dynamic Proxy: how to handle nested method calls
问题描述
我正在尝试学习Java中的动态代理.
I'm trying to learn Dynamic Proxies in Java.
我知道它们是如何工作的,但我找不到我的问题的解决方案:给定一个接口及其使用方法a(),b()和c()的实现,它们嵌套在一起(比如说a()调用b()并调用c()),我想代理我的对象以记录对方法的每次调用.
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.
所以我编写了自己的InvocationHandler代码,例如invoke()方法在执行之前打印了一条日志行.
So I code my InvocationHandler such as the invoke() method prints a log-line before the execution.
但是当我调用proxy.a()时,只会记录方法a()的调用,而不记录整个方法链.
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?
推荐答案
对象本身不知道它正在被代理,因此当a()调用b()时,它将是一个普通的内部对象" "称呼.
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.
这篇关于动态代理:如何处理嵌套方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!