JDK 代理
JDK 代理是 Java 动态代理的一种实现方式,它是通过 Java 反射机制来实现的。JDK 代理要求被代理的类必须实现一个或多个接口,因为它是基于接口的代理。
使用步骤:
定义接口: 定义一个接口,它是被代理类和代理类都要实现的接口。
public interface MyInterface { void doSomething(); }
实现真实对象类: 实现接口的真实对象类。
public class RealObject implements MyInterface { public void doSomething() { System.out.println("RealObject is doing something."); } }
创建代理对象: 使用 Proxy.newProxyInstance() 方法创建代理对象。
RealObject realObject=new RealObject(); MyInterface proxyInstance = (MyInterface) Proxy.newProxyInstance(RealObject.class.getClassLoader(), RealObject.class.getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before invoking method."); Object result = method.invoke(realObject, args); System.out.println("After invoking method."); return result; } }); proxyInstance.doSomething();
CGLIB 代理
CGLIB 代理是通过生成被代理类的子类来实现的,因此不要求被代理类实现接口,它可以代理没有无参构造函数的类。
创建代理对象: 使用 Enhancer 类创建代理对象。
//代理是子类型,目标是父类型 RealObject proxy = (RealObject) Enhancer.create(RealObject.class, new MethodInterceptor() { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("Before invoking method."); Object result = methodProxy.invokeSuper(o, args); // Object invoke = methodProxy.invoke(realObject, args); System.out.println("After invoking method."); return result; } }); proxy.doSomething();
RealObject realObject=new RealObject();