zoukankan      html  css  js  c++  java
  • 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     }  
  • 相关阅读:
    switch多分枝语句
    自动扫描判断数组奇偶 直接在控制台输入
    if else语句
    1231作业
    字符集和字符编码
    12.28作业
    置顶广告
    图片库
    js实现隔行换色及其鼠标滑过变色
    【转载】display:inline-block兼容ie6/7的写法
  • 原文地址:https://www.cnblogs.com/zengdan-develpoer/p/3875324.html
Copyright © 2011-2022 走看看