通俗易懂 快速理解 JDK动态代理 和 cglib动态代理
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
JDK动态代理和Cglib动态代理是Java中实现AOP(面向切面编程)的两种方式。
- JDK动态代理:
JDK动态代理是通过java.lang.reflect.Proxy类和java.lang.reflect.InvocationHandler接口实现的。
Proxy类通过反射机制创建代理类,InvocationHandler接口用来处理代理实例上的方法调用,并返回相应的结果。
例子:
// 实现InvocationHandler接口
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method invoke");
Object result = method.invoke(target, args);
System.out.println("After method invoke");
return result;
}
}
// 使用
public class Test {
public static void main(String[] args) {
Hello hello = new HelloImpl();
InvocationHandler handler = new MyInvocationHandler(hello);
Hello helloProxy = (Hello) Proxy.newProxyInstance(
hello.getClass().getClassLoader(),
hello.getClass().getInterfaces(),
handler);
helloProxy.sayHello();
}
}
- Cglib动态代理:
Cglib是一个强大的高性能的代码生成包,它可以在运行期动态生成某个类的子类,并覆盖其中特定的方法。
例子:
// 实现MethodInterceptor接口
public class MyMethodInterceptor implements MethodInterceptor {
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("Before method invoke");
Object result = proxy.invokeSuper(obj, args);
System.out.println("After method invoke");
return result;
}
}
// 使用
public class Test {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(HelloImpl.class);
enhancer.setCallback(new MyMethodInterceptor());
HelloImpl hello = (HelloImpl) enhancer.create();
hello.sayHello();
}
}
JDK动态代理通常用于代理实现了接口的类,而Cglib动态代理用于代理没有实现接口的类或私有方法,它是通过继承被代理类来实现的。
评论已关闭