What
- 代理模式
- Java的一种设计模式, 他的特征是与委托类有相同的接口,但是并不具体实现真正的服务
- 作用:
- 消息预处理
- 过滤消息
- 把消息转发给委托类
- 消息的事后处理
- 代理的分类:
- 静态代理:把已存在的编译文件重新编译
- 动态代理:在程序运行的时候通过反射机制动态创建
- JAVA的动态代理主要是:
- JDK自带的proxy
- cglib (code generation library)
- 什么是ASM?
- 一个字节码操控框架,可以增强既有类的功能、生成新的类。
- JAVA class被描述成一棵树, asm使用visitor模式来遍历整个二进制结构
JDK-InvocationHandler
- 委托类必须实现接口,不能代理普通类(没有接口的类)
- 代理类必须实现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;
}
- 获取代理的方法
Proxy.newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
//for example, interface BookInterface
BookInterface proxy = (BookInterface)Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
- 缺陷:
- 只能对接口进行代理
- 速度慢
CGLIB
- 优点:
- 基于字节码操作框架asm封装,性能高
- 能代理非接口的普通java类
2.实现方式:创建一个被代理对象的子类并且拦截所有的非final方法调用(包括从Object中继承的toString和hashCode方法
Performance
- JDK InvocationHandler代理调用方法,比直接调用方法慢很多, 据2008年的一篇文章【参考5】,倍数是1.63倍