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.
Java code
- Import Java.lang.reflect.Field;
- Import Org.springframework.aop.framework.AdvisedSupport;
- Import Org.springframework.aop.framework.AopProxy;
- Import Org.springframework.aop.support.AopUtils;
- Public class Aoptargetutils {
- /**
- * Get target object
- * @param proxy Object
- * @return
- * @throws Exception
- */
- public Static Object Gettarget (object proxy) throws Exception {
- if (! Aoputils.isaopproxy (proxy)) {
- return proxy; //Not a proxy object
- }
- if (aoputils.isjdkdynamicproxy (proxy)) {
- return Getjdkdynamicproxytargetobject (proxy);
- } else { //cglib
- return Getcglibproxytargetobject (proxy);
- }
- }
- private Static object Getcglibproxytargetobject (object proxy) throws Exception {
- 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 ();
- return target;
- }
- private Static object Getjdkdynamicproxytargetobject (object proxy) throws Exception {
- 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 ();
- return target;
- }
- }
Gets the target object tool class for the proxy object proxy in spring