美文网首页
获取JDK动态代理/CGLIB代理对象代理的目标对象

获取JDK动态代理/CGLIB代理对象代理的目标对象

作者: AbsurdOS | 来源:发表于2017-05-16 11:27 被阅读0次

    公司基础框架是通过反射来获取controller层的,会丢失aop的东西,修改框架拿到被代理的对象就行了。

        public static Object getTarget(Object proxy) {
            if (!AopUtils.isAopProxy(proxy)) {
                return proxy;// 不是代理对象
            }
            if (AopUtils.isJdkDynamicProxy(proxy)) {
                return getJdkDynamicProxyTargetObject(proxy);
            } else { // cglib
                return getCglibProxyTargetObject(proxy);
            }
        }
    
    private static Object getCglibProxyTargetObject(Object proxy) {
            try{
                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;
            } catch(Exception e){
                e.printStackTrace();
                return null;
            }
        }
        
    
        private static Object getJdkDynamicProxyTargetObject(Object proxy) {
            try{
                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;
            } catch(Exception e){
                e.printStackTrace();
                return null;
            }
        }
    

    学习自:http://jinnianshilongnian.iteye.com/blog/1613222
    mark一下

    相关文章

      网友评论

          本文标题:获取JDK动态代理/CGLIB代理对象代理的目标对象

          本文链接:https://www.haomeiwen.com/subject/qwqlxxtx.html