文章转自
http://www.cnblogs.com/icejoywoo/archive/2011/06/05/2072970.html
cglib 是一个强大的, 高效高质的代码生成库.
简单的使用方法
Enhancer中有几个常用的方法, setSuperClass和setCallback, 设置好了SuperClass后, 可以使用create制作代理对象了
Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(EnhancerDemo.class); enhancer.setCallback(new MethodInterceptorImpl()); EnhancerDemo demo = (EnhancerDemo) enhancer.create();
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; } }
完整代码如下:
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$$EnhancerByCGLIB$$bc9b2066
@1621e42
|
我们可以看到System.out.println(demo), demo首先调用了toString()方法, 然后又调用了hashCod, 我们可以查看toString的源代码
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }