通过对cglib的核心类enhancer的分析,该类库实现动态代理的方式是:
Enhancer.java
......
/**
* Set the class which the generated class will extend. As a convenience,
* if the supplied superclass is actually an interface, <code>setInterfaces</code>
* will be called with the appropriate argument instead.
* A non-interface argument must not be declared as final, and must have an
* accessible constructor.
* @param superclass class to extend or interface to implement
* @see #setInterfaces(Class[])
*/
public void setSuperclass(Class superclass) {
if (superclass != null && superclass.isInterface()) {
setInterfaces(new Class[]{ superclass });
} else if (superclass != null && superclass.equals(Object.class)) {
// affects choice of ClassLoader
this.superclass = null;
} else {
this.superclass = superclass;
}
}
......
通过该方法的注释,我们可以看出cglib其实是通过生成新的类来实现代理的:
1、初始化方法拦截器MethodInterceptor。
2、根据继承(类:extends,接口:implements)传人的被代理类,并注册相应的方法拦截器为callback。
通过上面两步骤就可以实现代理了
总结:还没有把源码都看一遍,所以还有部分细节需要求证。