JDK动态代理与CGLib动态代理在使用上的异同点
时间: 2024-04-13 17:21:13 浏览: 137
JDK动态代理和CGLib动态代理都是实现AOP编程的方式,它们的使用上有以下异同点:
1. JDK动态代理只能代理实现了接口的类,而CGLib动态代理可以代理没有实现接口的类。
2. JDK动态代理是通过反射来实现的,而CGLib动态代理使用的是继承。
3. JDK动态代理在生成代理对象时,需要传入一个InvocationHandler对象,而CGLib动态代理在生成代理对象时,需要继承MethodInterceptor类,并重写intercept()方法。
4. JDK动态代理生成的代理对象性能比CGLib动态代理生成的代理对象性能要低。
下面是一个JDK动态代理的例子:
```python
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface Subject {
void request();
}
class RealSubject implements Subject {
public void request() {
System.out.println("RealSubject request");
}
}
class DynamicProxy implements InvocationHandler {
private Object subject;
public DynamicProxy(Object subject) {
this.subject = subject;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before calling " + method);
method.invoke(subject, args);
System.out.println("after calling " + method);
return null;
}
}
public class Main {
public static void main(String[] args) {
RealSubject realSubject = new RealSubject();
InvocationHandler handler = new DynamicProxy(realSubject);
Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(),
realSubject.getClass().getInterfaces(), handler);
subject.request();
}
}
```
下面是一个CGLib动态代理的例子:
```python
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
class RealSubject {
public void request() {
System.out.println("RealSubject request");
}
}
class DynamicProxy implements MethodInterceptor {
private Object subject;
public DynamicProxy(Object subject) {
this.subject = subject;
}
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
System.out.println("before calling " + method);
proxy.invoke(subject, args);
System.out.println("after calling " + method);
return null;
}
}
public class Main {
public static void main(String[] args) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(RealSubject.class);
enhancer.setCallback(new DynamicProxy(new RealSubject()));
RealSubject subject = (RealSubject) enhancer.create();
subject.request();
}
}
```
阅读全文