Spring Aop中,获取被代理类的工具

在实际应用中,顺着过去就是一个类被代理。反过来,可能需要逆向进行,拿到被代理的类,实际工作中碰到了,就拿出来分享下。

 1 /**
 2      * 获取被代理类的Object
 3      * @author Monkey
 4      */
 5     public Object getTarget(Object proxy) throws Exception {  
 6         
 7         if(!AopUtils.isAopProxy(proxy)) {  
 8             //不是代理对象  
 9             return proxy;
10         }  
11           
12         if(AopUtils.isJdkDynamicProxy(proxy)) {  
13             return getJdkDynamicProxyTargetObject(proxy);  
14         } else { //cglib  
15             return getCglibProxyTargetObject(proxy);  
16         }    
17     }  
 1 /**
 2      * CGLIB方式被代理类的获取
 3      * @author Monkey
 4      * 
 5      */
 6     private Object getCglibProxyTargetObject(Object proxy) throws Exception {  
 7         Field h = proxy.getClass().getDeclaredField("CGLIB$CALLBACK_0");  
 8         h.setAccessible(true);  
 9         Object dynamicAdvisedInterceptor = h.get(proxy);  
10         Field advised = dynamicAdvisedInterceptor.getClass().getDeclaredField("advised");  
11         advised.setAccessible(true);  
12         Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();   
13         return target;  
14     }  
 1 /**
 2      * JDK动态代理方式被代理类的获取
 3      * @author Monkey
 4      * 
 5      */
 6     private Object getJdkDynamicProxyTargetObject(Object proxy) throws Exception {  
 7         Field h = proxy.getClass().getSuperclass().getDeclaredField("h");  
 8         h.setAccessible(true);  
 9         AopProxy aopProxy = (AopProxy) h.get(proxy);  
10         Field advised = aopProxy.getClass().getDeclaredField("advised");  
11         advised.setAccessible(true);  
12         Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();  
13         return target;  
14     }  

 

Spring Aop中,获取被代理类的工具,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。