JDK和CGLIB動(dòng)態(tài)代理是Java編程中經(jīng)常使用的兩種代理方式,它們都有助于簡(jiǎn)化代碼和提高應(yīng)用程序的靈活性。
JDK動(dòng)態(tài)代理是Java標(biāo)準(zhǔn)庫的一部分,它使用Java Reflection API在運(yùn)行時(shí)生成代理對(duì)象。代理對(duì)象的實(shí)現(xiàn)由Java編譯器或者JVM自動(dòng)生成,無需手動(dòng)編寫代理類。
interface Subject { void request(); } class RealSubject implements Subject { public void request() { System.out.println("RealSubject"); } } class ProxyHandler implements InvocationHandler { private Object target; public ProxyHandler(Object target) { this.target = target; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object result = null; // do something before result = method.invoke(target, args); // do something after return result; } } class Test { public static void main(String[] args) { Subject realSubject = new RealSubject(); InvocationHandler handler = new ProxyHandler(realSubject); Subject proxy = (Subject) Proxy.newProxyInstance(realSubject.getClass().getClassLoader(), realSubject.getClass().getInterfaces(), handler); proxy.request(); // RealSubject } }
CGLIB動(dòng)態(tài)代理是一個(gè)第三方工具包,它通過生成代理類的方式實(shí)現(xiàn)代理。與JDK動(dòng)態(tài)代理不同,CGLIB動(dòng)態(tài)代理可以代理非接口類型的類。
class RealSubject { public void request() { System.out.println("RealSubject"); } } class ProxyHandler implements MethodInterceptor { private Object target; public ProxyHandler(Object target) { this.target = target; } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Object result = null; // do something before result = proxy.invoke(target, args); // do something after return result; } } class Test { public static void main(String[] args) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(RealSubject.class); enhancer.setCallback(new ProxyHandler(new RealSubject())); RealSubject proxy = (RealSubject) enhancer.create(); proxy.request(); // RealSubject } }
總的來說,JDK動(dòng)態(tài)代理適用于代理接口類型的類,使用簡(jiǎn)單方便;CGLIB動(dòng)態(tài)代理適用于代理非接口類型的類,功能更加強(qiáng)大。在實(shí)際開發(fā)中,應(yīng)根據(jù)具體情況選擇合適的代理方式。