Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unwrap the original object from a dynamic proxy

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.

like image 779
MRalwasser Avatar asked Dec 10 '10 13:12

MRalwasser


People also ask

What is dynamic proxy object?

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

What is a dynamic proxy invocation handler?

A dynamic proxy can be thought of as a kind of Facade, but one that can pretend to be an implementation of any interface. Under the cover, it routes all method invocations to a single handler – the invoke() method.

How are JDK dynamic proxies?

JDK dynamic proxy is available with the JDK. It can be only proxy by interface so target class needs to implement interface. In your is implementing one or more interface then spring will automatically use JDK dynamic proxies. On the other hand, CGLIB is a third party library which spring used for creating proxy.

Is JDK a dynamic proxy?

JDK proxy (dynamic proxy): The JDK proxy creates a new proxy object by implementing interfaces of the target object and delegating method calls. CGLIB proxy: The CGLIB proxy creates a new proxy object by extending the target object and delegating method calls.


2 Answers

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()
like image 69
iirekm Avatar answered Sep 29 '22 07:09

iirekm


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.

like image 45
NPE Avatar answered Sep 29 '22 06:09

NPE