All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.stylefeng.roses.kernel.scanner.modular.util.AopTargetUtils Maven / Gradle / Ivy

There is a newer version: 2.2.13
Show newest version
/**
 * Copyright 2018-2020 stylefeng & fengshuonan ([email protected])
 * 

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at *

* http://www.apache.org/licenses/LICENSE-2.0 *

* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.stylefeng.roses.kernel.scanner.modular.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.aop.framework.AdvisedSupport; import org.springframework.aop.framework.AopProxy; import org.springframework.aop.support.AopUtils; import java.lang.reflect.Field; /** * 获取代理原始对象的工具 * * @author fengshuonan * @Date 2018/2/21 17:09 */ public class AopTargetUtils { private static Logger logger = LoggerFactory.getLogger(AopTargetUtils.class); public static Object getTarget(Object proxy) { if (!AopUtils.isAopProxy(proxy)) { return proxy;//不是代理对象 } try { if (AopUtils.isJdkDynamicProxy(proxy)) { return getJdkDynamicProxyTargetObject(proxy); } else { return getCglibProxyTargetObject(proxy); } } catch (Exception e) { logger.error("获取代理对象异常", e); return null; } } 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); return ((AdvisedSupport) advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget(); } 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); return ((AdvisedSupport) advised.get(aopProxy)).getTargetSource().getTarget(); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy