Last night a buddy needs to get the target object of the proxy object, find the document found no corresponding tool class, so I wrote a share to everyone. Can obtain the target object of the JDK dynamic Agent/cglib proxy object agent.
Problem Description::
I now have a tricky problem, to save the object through the spring managed service class, which is obtained through reflection, and it is experimentally discovered that the class can only reflect the method that Sservice implements the interface, and the methods of the extends class do not appear. Debug found that this Servie instance was replaced by spring with the Jdkdynmicproxy class, rather than the original object, it is only the service inherited interface method, and there is no extends super class method, how to invoke the native object method !!!!!
Call the GetClass (). GetName () method with the managed Spring service class, and find out that the output is $proxy43 such things!!
Getting the target object in this way is unreliable, or any way to get the target object is unreliable, because the target object is stored in the Targetsource,targetsource, but Targetsource has many implementations, By default we use Singletontargetsource, but there are other things like Threadlocaltargetsource, Commonspooltargetsource and so on.
This is why spring does not provide the API to get the target object.
ImportJava.lang.reflect.Field; ImportOrg.springframework.aop.framework.AdvisedSupport; ImportOrg.springframework.aop.framework.AopProxy; Importorg.springframework.aop.support.AopUtils; Public classAoptargetutils {/*** Get target object *@paramProxy Object *@return * @throwsException*/ Public StaticObject Gettarget (Object proxy)throwsException {if(!aoputils.isaopproxy (proxy)) { returnProxy//not a proxy object } if(Aoputils.isjdkdynamicproxy (proxy)) {returngetjdkdynamicproxytargetobject (proxy); } Else{//Cglib returngetcglibproxytargetobject (proxy); } } Private StaticObject Getcglibproxytargetobject (Object proxy)throwsException {Field h= Proxy.getclass (). Getdeclaredfield ("Cglib$callback_0"); H.setaccessible (true); Object Dynamicadvisedinterceptor=h.get (proxy); Field advised= Dynamicadvisedinterceptor.getclass (). Getdeclaredfield ("advised"); Advised.setaccessible (true); Object Target=((Advisedsupport) Advised.get (Dynamicadvisedinterceptor)). Gettargetsource (). Gettarget (); returnTarget; } Private StaticObject Getjdkdynamicproxytargetobject (Object proxy)throwsException {Field h= Proxy.getclass (). Getsuperclass (). Getdeclaredfield ("H"); H.setaccessible (true); Aopproxy Aopproxy=(Aopproxy) h.get (proxy); Field advised= Aopproxy.getclass (). Getdeclaredfield ("advised"); Advised.setaccessible (true); Object Target=((Advisedsupport) Advised.get (Aopproxy)). Gettargetsource (). Gettarget (); returnTarget; } }
Gets the target object tool class for the proxy object proxy in spring