网上搜CGLIB动态代理,几乎所有的博文都只给了示例代码而缺少对代码的解释说明(特别是关键的intercept函数),看完实在是云里雾里。所以,这篇博文将带你从源码的角度来理解intercept函数。
前言
关于如何使用CGLIB创建动态代理,网上已经有很多资料,这里就不再赘述。本文将使用如下代码进行分析,如果你还看不懂下面的代码,请先自行搜索资料看懂后再继续后面的内容。
import net.sf.cglib.core.DebuggingClassWriter;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;
class Human {
public void say() {
System.out.println("I am super man~~~");
}
}
class ProxyWithCglib {
public static Object newProxy(Object object) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(object.getClass());
MyMethodInterceptor myMethodInterceptor = new MyMethodInterceptor();
myMethodInterceptor.bind(object);
enhancer.setCallback(myMethodInterceptor);
return enhancer.create();
}
}
class MyMethodInterceptor implements MethodInterceptor {
private Object target;
public void bind(Object o) {
this.target = o;
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("pre-function logic.");
Object ret = methodProxy.invokeSuper(o, objects);
System.out.println("post-function logic.");
return ret;
}
}
public class Test {
public static void main(String[] args) {
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "./debug_info"); // 用于输出CGLIB产生的类
Human humanProxy = (Human) ProxyWithCglib.newProxy(new Human());
System.out.println(humanProxy.getClass());
humanProxy.say();
}
}
简要对代码进行一些说明:
- Human类为被代理对象;
- MyMethodInterceptor中的target属性用于保存被代理对象的实例;
- ProxyWithCglib类的静态方法newProxy用于创建代理对象实例;
- 运行代码即可在debug_info目录下看到运行时生成的类,这将用于我们后续的分析
理解intercept的四个参数
要理解intercept方法的参数的含义,一个不错的办法就是看看运行时调用intercept方法的时候传入的参数是什么。
为了找到在哪里调用了intercept方法,我们从main方法的最后一行:
humanProxy.say();
开始跟。
根据
System.out.println(humanProxy.getClass());
这一行我们可以知道运行时生成的类为:
Human$$EnhancerByCGLIB$$xxxxxx
这个类的代码为(为了便于阅读,只放出我们关注的部分):
public class Human$$EnhancerByCGLIB$$1a29a813 extends Human implements Factory {
private boolean CGLIB$BOUND;
public static Object CGLIB$FACTORY_DATA;
private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
private static final Callback[] CGLIB$STATIC_CALLBACKS;
private MethodInterceptor CGLIB$CALLBACK_0;
private static Object CGLIB$CALLBACK_FILTER;
private static final Method CGLIB$say$0$Method;
private static final MethodProxy CGLIB$say$0$Proxy;
private static final Object[] CGLIB$emptyArgs;
private static final Method CGLIB$equals$1$Method;
private static final MethodProxy CGLIB$equals$1$Proxy;
private static final Method CGLIB$toString$2$Method;
private static final MethodProxy CGLIB$toString$2$Proxy;
private static final Method CGLIB$hashCode$3$Method;
private static final MethodProxy CGLIB$hashCode$3$Proxy;
private static final Method CGLIB$clone$4$Method;
private static final MethodProxy CGLIB$clone$4$Proxy;
static void CGLIB$STATICHOOK1() {
CGLIB$THREAD_CALLBACKS = new ThreadLocal();
CGLIB$emptyArgs = new Object[