被代理类
public class Human {
void doThings() {
System.out.println("Human");
}
}
代理类
public class CglibProxyHuman implements MethodInterceptor {
public Object getProxyInstance(Object target) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this); //将自己传给增强类,调用this.intercept
return enhancer.create();
}
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
System.out.println("before target method...");
Object result = methodProxy.invokeSuper(o, objects);
System.out.println("after target method...");
return result;
}
}
测试代码
public static void main(String[] args) {
//调试查看动态代理生成文件
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "f:\\cglib");
Human human= new Human();
Human humanProxy=(Human)new CglibProxyHuman().getProxyInstance(human);
humanProxy.doThings();
}
查看动态代理生成文件,存储在 f:\\cglib
System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY, "f:\\cglib");
增强类
humanProxy对象对应的动态生成的增强类 Human$ $EnhancerByCGLIB$$b7eedfef
import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class Human$$EnhancerByCGLIB$$b7eedfef extends Human implements Factory {
private boolean CGLIB$BOUND;
private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
private static final Callback[] CGLIB$STATIC_CALLBACKS;
private MethodInterceptor CGLIB$CALLBACK_0;
private static final Method CGLIB$doThings$0$Method;
private static final MethodProxy CGLIB$doThings$0$Proxy;
private static final Object[] CGLIB$emptyArgs;
private static final Method CGLIB$finalize$1$Method;
private static final MethodProxy CGLIB$finalize$1$Proxy;
private static final Method CGLIB$equals$2$Method;
private static final MethodProxy CGLIB$equals$2$Proxy;
private static final Method CGLIB$toString$3$Method;
private static final MethodProxy CGLIB$toString$3$Proxy;
private static final Method CGLIB$hashCode$4$Method;
private static final MethodProxy CGLIB$hashCode$4$Proxy;
private static final Method CGLIB$clone$5$Method;
private static final MethodProxy CGLIB$clone$5$Proxy;
static void CGLIB$STATICHOOK1() {
CGLIB$THREAD_CALLBACKS = new ThreadLocal();
CGLIB$emptyArgs = new Object[0];
Class