cglib 是一个强大的, 高效高质的代码生成库.
简单的使用方法
Enhancer中有几个常用的方法, setSuperClass和setCallback, 设置好了SuperClass后, 可以使用create制作代理对象了
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(EnhancerDemo.class);
enhancer.setCallback(new MethodInterceptorImpl());
EnhancerDemo demo = (EnhancerDemo) enhancer.create();
实现MethodInterceptor接口
private static class MethodInterceptorImpl implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.out.println("Before invoke " + method);
Object result = proxy.invokeSuper(obj, args);
System.out.println("After invoke" + method);
return result;
}
}
intercept方法, Object result = proxy.invokeSuper(obj, args)调用了原来的方法, 在这个调用前后可以添加其他的逻辑, 相当于AspectJ的around
完整代码如下:
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class EnhancerDemo {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(EnhancerDemo.class);
enhancer.setCallback(new MethodInterceptorImpl());
EnhancerDemo demo = (EnhancerDemo) enhancer.create();
demo.test();
System.out.println(demo);
}
public void test() {
System.out.println("EnhancerDemo test()");
}
private static class MethodInterceptorImpl implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable {
System.err.println("Before invoke " + method);
Object result = proxy.invokeSuper(obj, args);
System.err.println("After invoke" + method);
return result;
}
}
}
运行结果如下:
Before invoke public void EnhancerDemo.test()
EnhancerDemo test()
After invokepublic void EnhancerDemo.test()
Before invoke public java.lang.String java.lang.Object.toString()
Before invoke public native int java.lang.Object.hashCode()
After invokepublic native int java.lang.Object.hashCode()
After invokepublic java.lang.String java.lang.Object.toString()
EnhancerDemo
我们可以看到System.out.println(demo), demo首先调用了toString()方法, 然后又调用了hashCode,
生成的对象为EnhancerDemo