zoukankan      html  css  js  c++  java
  • java动态代理--cglib

    cglib的优点:

      1. 性能高。CGLib底层采用ASM字节码生成框架,使用字节码技术生成代理类,比使用Java反射效率要高。

      2. 无需实现接口。Java通过java.lang.reflect.Proxy和java.lang.reflect.InvocationHandler实现的动态代理必须实现接口,但现实中往往是没有接口的。

    代码:

      1. 随意定义一个类。  

    package pr.cgl.cglib;

    /**
    * Created by LL on 2015/8/27.
    */
    public class Tank {
    public void move(){
    System.out.println("Tank is moving...");
    }
    public void action(){
    System.out.println("Tank is start firing...");
    }
    }
    2. 实现  
    package pr.cgl.cglib;

    import net.sf.cglib.proxy.Enhancer;
    import net.sf.cglib.proxy.MethodInterceptor;
    import net.sf.cglib.proxy.MethodProxy;
    import java.lang.reflect.Method;
    /**
    * Created by LL on 2015/8/27.
    */
    public class CglibProxy implements MethodInterceptor {

    //要代理的原始对象
    private Object obj;

    public Object createProxy(Object target) {
    this.obj = target;
    Enhancer enhancer = new Enhancer();
    enhancer.setSuperclass(target.getClass());// 设置代理目标
    enhancer.setCallback(new CglibProxy());// 设置回调
    enhancer.setClassLoader(target.getClass().getClassLoader());
    return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    Long start = System.currentTimeMillis();
    System.out.println("start="+start);
    Object result = methodProxy.invokeSuper(o, objects);
    Long end = System.currentTimeMillis();
    System.out.println("end="+end);
    System.out.println("time spent :"+((end - start))+" "+result);
    return result;
    }
    }
    3. 测试 
    package pr.cgl.cglib;

    /**
    * Created by LL on 2015/8/27.
    */
    public class Test3 {
    public static void main(String[] args) {
    Tank tank = new Tank();
    CglibProxy proxy = new CglibProxy();
    Tank t = (Tank)proxy.createProxy(tank);
    t.action();
    }

    }
    输出:

      start=1440662005592
      Tank is start firing...
      end=1440662005605
      time spent :13 null

  • 相关阅读:
    解决uc浏览器不支持vw单位的方法
    调整网页适应移动端设备
    鼠标滚轮事件
    Sublime Text 3 快捷键总结(拿走)
    HTML+CSS图文排版
    焦点轮播图(一)
    前端各种库的在线引入地址
    HTML表格的基本操作
    23 服务的绑定启动Demo3
    23 服务的启动Demo2
  • 原文地址:https://www.cnblogs.com/cglWorkBook/p/4763656.html
Copyright © 2011-2022 走看看