java 如何从动态代理解包原始对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4409456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unwrap the original object from a dynamic proxy
提问by MRalwasser
what's the best approach to unwrap a dynamic proxy to retrieve the original object beneath?
The dynamic proxy has been created using java.lang.reflect.Proxy.newProxyInstance()
展开动态代理以检索下面的原始对象的最佳方法是什么?已使用创建动态代理java.lang.reflect.Proxy.newProxyInstance()
Thank you.
谢谢你。
回答by iirekm
There's no good method: Proxy.getInvocationHandler(proxy) returns handler, but the problem is to extract the original object from the handler. If your handler is an anonymous class, the only way to extract original object is to use reflection and extract original from field named val$something - very ugly method. Better way is to create non-anonymous handler class with a getter, then you do:
没有好的方法:Proxy.getInvocationHandler(proxy) 返回处理程序,但问题是从处理程序中提取原始对象。如果您的处理程序是匿名类,则提取原始对象的唯一方法是使用反射并从名为 val$something 的字段中提取原始对象 - 非常丑陋的方法。更好的方法是使用 getter 创建非匿名处理程序类,然后执行以下操作:
((YourHandler)Proxy.getInvocationHandler(proxy)).getOriginalObject()
回答by NPE
Each proxy has an InvocationHandler
associated with it. Only the InvocationHandler
knows which object (if any) underlies the proxy. If you control the creation of the proxy, then you can supply your own InvocationHandler
that will have the extra functionality that you desire (i.e. will be able to disclose the underlying object.) If you don't, then I am afraid you're out of luck.
每个代理都有一个InvocationHandler
与之关联的。只有InvocationHandler
知道哪个对象(如果有)是代理的基础。如果您控制代理的创建,那么您可以提供自己的InvocationHandler
具有您想要的额外功能的功能(即能够公开底层对象。)如果您不这样做,那么恐怕您已经出局了运气。
回答by Peter Lawrey
You can use the Proxy.getInvocationHandler(proxy) method to obtain the original InvocationHandler.
您可以使用 Proxy.getInvocationHandler(proxy) 方法来获取原始的 InvocationHandler。