Cglib简单学习(2)
来源:互联网 发布:乐乎lofter军人大雕 编辑:程序博客网 时间:2024/04/30 10:58
文章转自
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();
实现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$$EnhancerByCGLIB$$bc9b2066
@1621e42
我们可以看到System.out.println(demo), demo首先调用了toString()方法, 然后又调用了hashCod, 我们可以查看toString的源代码
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }
生成的对象为EnhancerDemo$$EnhancerByCGLIB$$bc9b2066的实例, 这个类是运行时由cglib产生的
- Cglib简单学习(2)
- Cglib简单学习(1)
- spring学习笔记6--简单模拟实现AOP(cglib版)
- 简单动态代理实例(使用cglib)
- CGlib简单介绍
- CGlib简单介绍
- CGlib简单介绍
- CGlib简单介绍
- CGlib简单介绍
- CGLIB 简单介绍
- CGlib简单介绍
- CGlib简单介绍
- CGlib简单介绍
- CGlib简单介绍
- CGlib简单介绍
- CGlib简单介绍
- cglib简单模拟aop
- CGlib简单介绍
- C/C++面试题1
- 江城春雨
- 哭着,在梦里
- 概率题目
- 中国为什么需要民主制度
- Cglib简单学习(2)
- 用FASTREPORT实现WEB应用中自定义报表
- 太阳,是我的家
- K(CD1684)
- I(cd1682)
- 雪啊……雪,爱你!
- 别了,黑夜!
- java locale详解
- (概率)G(CD1680)