概念
在運行期間動態(tài)的創(chuàng)建接口的實現。
通過生成的代理類墨吓,可以完成對接口的實現。
關鍵類和接口
處理接口方法的接口 InvocationHandler
代理生成類 Proxy
典型代碼
創(chuàng)建Foo接口的代理實現
創(chuàng)建某一接口 Foo 的代理:
InvocationHandler handler = new MyInvocationHandler(...);
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
步驟
1.對接口方法的處理
首先需要實現InvocationHandler
接口,重寫invoke方法
public class MyInvocationHandler implements InvocationHandler{
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//..所有方法的調用都會在這里執(zhí)行
}
}
2.通過Proxy的靜態(tài)方法生成代理類萝毛,或代理對象。
代理對象
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class },
handler);
代理類方式
InvocationHandler handler = new MyInvocationHandler(...);
Class proxyClass = Proxy.getProxyClass(
Foo.class.getClassLoader(), new Class[] { Foo.class });
Foo f = (Foo) proxyClass.
getConstructor(new Class[] { InvocationHandler.class }).
newInstance(new Object[] { handler });
常見用例
動態(tài)代理常被應用到以下幾種情況中
數據庫連接以及事物管理
單元測試中的動態(tài)Mock對象
自定義工廠與依賴注入(DI)容器之間的適配器
類似AOP的方法攔截器