动态代理的两种方式
- 基于接口的动态代理
- 基于子类的动态代理
基于接口的动态代理
提供者:JDK 官方的 Proxy 类。
要求:被代理类最少实现一个接口。
实现方式
使用 JDK 官方的 Proxy 类创建代理对象
接口 变量名 = (接口) Proxy.newProxyInstance(被代理对象.getClass().getClassLoader(), 被代理对象.getClass().getInterfaces(), new InvocationHandler() {
});
示例
IActor proxyActor = (IActor) Proxy.newProxyInstance(actor.getClass().getClassLoader(), actor.getClass().getInterfaces(), new InvocationHandler() {
});
基于子类的动态代理
提供者:第三方的 CGLib,如果报 asmxxxx 异常,需要导入 asm.jar。
要求:被代理类不能用 final 修饰的类(最终类)。
实现方式
使用 CGLib 的 Enhancer 类创建代理对象
被代理类 变量名 = (被代理类) Enhancer.create(被代理类.getClass(),new MethodInterceptor() {
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
});
示例
Actor cglibActor = (Actor) Enhancer.create(actor.getClass(),new MethodInterceptor() {
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
});