How to unwrap the original object from a dynamic proxy

谁都会走 提交于 2019-12-19 05:44:51

问题


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()

Thank you.


回答1:


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.




回答2:


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:

((YourHandler)Proxy.getInvocationHandler(proxy)).getOriginalObject()



回答3:


You can use the Proxy.getInvocationHandler(proxy) method to obtain the original InvocationHandler.



来源:https://stackoverflow.com/questions/4409456/how-to-unwrap-the-original-object-from-a-dynamic-proxy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!