本文共 3198 字,大约阅读时间需要 10 分钟。
JDK和CGILB两种动态代理实现方式各有特点,了解其实现机制对于开发有重要意义。本文将从 InvocationHandler 与 Proxy(JDK实现)、MethodInterceptor 与 Enchancer(CGILB实现)两个方面进行对比分析。
JDK动态代理的核心组件包括 InvocationHandler 和 Proxy。
Proxy 是动态代理的核心实现类,主要负责根据指定接口生成动态代理类。 Proxy 类提供了两个重要方法:
Proxy.newProxyInstance:用于根据指定的接口生成动态代理对象。
loader
:类加载器,负责生成代理类所需的类加载。interfaces
:接口数组,指定需要代理接口。handler
:InvocationHandler 实例,负责调用目标方法。InvocationHandler 接口:定义了动态代理的逻辑处理方法。
invoke
方法核心逻辑: // 目标类interface Subject { void rent(); void hello(String str);}class RealSubject implements Subject { @Override void rent() { System.out.println("I want to rent my house"); } @Override void hello(String str) { System.out.println("hello: " + str); }}// 动态代理接口实现class DynamicProxy implements InvocationHandler { private RealSubject subject; constructor RealSubject subject) { this.subject = subject; } @Override public Object invoke(Object object, Method method, Object[] args) { System.out.println("调用前:" + method.getName()); method.invoke(subject, args); System.out.println("调用后"); return null; }}// 创建代理Subject subjectProxy = Proxy.newProxyInstance( DynamicProxy.class.getClassLoader(), RealSubject.class.getInterfaces(), new DynamicProxy(new RealSubject()));
调用代理对象 method:
Proxy0before rent houseMethod: public abstract void com.xiaoluo SUBJECT rent ()I want to rent my houseafter rent housebefore rent houseMethod: public abstract void com.xiaoluo SUBJECT hello (java.lang.String)hello: worldafter rent house
CGILB 与 JDK 的主要区别:
导入必要库:
cglib-nodep-2.2.jar
(无需_asm.jar包)cglib-2.2.jar
(需配合_asm.jar包使用)开发拦截器类:实现 MethodInterceptor
接口。
import java.lang.reflect.Method;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;public class TargetInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] params, MethodProxy proxy) throws Throwable { System.out.println("拦截前:" + method.getName()); Object result = proxy.invokeSuper(obj, params); System.out.println("拦截后:" + result); return result; }}
// 定义类型对象public static final TargetObject TARGET_OBJECT = new TargetObject();// 实现 EnhancerEnhancer enhancer = new Enhancer();enhancer.setSuperclass(TARGET_OBJECT.getClass());enhancer.setCallback(new TargetInterceptor());TARGET_OBJECT = enhancer.create();// 调用方法System.out.println(TARGET_OBJECT.method1("mmm1"));System.out.println(TARGET_OBJECT.method2(100));System.out.println(TARGET_OBJECT.method3(200));
---## 动态代理的核心选型- **选择 JDK 动态代理**:如果目标对象已实现特定接口,且对动态代理的逻辑要求较为基础。- **选择 CGILB 动态代理**:如果需要更灵活的方法拦截,而目标对象无需实现接口,或需对方法执行过程增强功能。
转载地址:http://fnryk.baihongyu.com/