首页 > 代码库 > Spring Aop中,获取被代理类的工具

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     }