Java动态代理(invocation handler、cglib)简析

What

  1. 代理模式
    • Java的一种设计模式, 他的特征是与委托类有相同的接口,但是并不具体实现真正的服务
    • 作用:
      • 消息预处理
      • 过滤消息
      • 把消息转发给委托类
      • 消息的事后处理
  2. 代理的分类:
    • 静态代理:把已存在的编译文件重新编译
    • 动态代理:在程序运行的时候通过反射机制动态创建
  3. JAVA的动态代理主要是:
    • JDK自带的proxy
    • cglib (code generation library)
  4. 什么是ASM?
    • 一个字节码操控框架,可以增强既有类的功能、生成新的类。
    • JAVA class被描述成一棵树, asm使用visitor模式来遍历整个二进制结构

JDK-InvocationHandler

  1. 委托类必须实现接口,不能代理普通类(没有接口的类)
  2. 代理类必须实现InvocationHandler的接口,例子如下:
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //do something before
        //execute, target is the real implemation class(Delegate)
        result = method.invoke(target, args);
       //do something after
        return result;
    }
  1. 获取代理的方法
Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)

//for example, interface BookInterface
BookInterface proxy = (BookInterface)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);  
  1. 缺陷:
    • 只能对接口进行代理
    • 速度慢

CGLIB

  1. 优点:
    • 基于字节码操作框架asm封装,性能高
    • 能代理非接口的普通java类

2.实现方式:创建一个被代理对象的子类并且拦截所有的非final方法调用(包括从Object中继承的toString和hashCode方法

Performance

  1. JDK InvocationHandler代理调用方法,比直接调用方法慢很多, 据2008年的一篇文章【参考5】,倍数是1.63倍

Reference

  1. java动态代理(JDK和cglib)
  2. AOP 的利器:ASM 3.0 介绍
  3. CGLIB(Code Generation Library)详解
  4. Decorating with dynamic proxies
  5. Benchmarking the cost of dynamic proxies
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容