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

 /**
* 获取被代理类的Object
* @author Monkey
*/
public Object getTarget(Object proxy) throws Exception { if(!AopUtils.isAopProxy(proxy)) {
//不是代理对象
return proxy;
} if(AopUtils.isJdkDynamicProxy(proxy)) {
return getJdkDynamicProxyTargetObject(proxy);
} else { //cglib
return getCglibProxyTargetObject(proxy);
}
}
 /**
* CGLIB方式被代理类的获取
* @author Monkey
*
*/
private 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);
Object target = ((AdvisedSupport)advised.get(dynamicAdvisedInterceptor)).getTargetSource().getTarget();
return target;
}
 /**
* JDK动态代理方式被代理类的获取
* @author Monkey
*
*/
private 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);
Object target = ((AdvisedSupport)advised.get(aopProxy)).getTargetSource().getTarget();
return target;
}
05-06 10:26