如果想在運行時生成新的對象,并且這個對象的類型是全新的,是現有系統中沒有的。就可以用Proxy類中的靜態方法newProxyInstance來實現。其API如下:
public static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler handler);
參數:
- loader: 類加載器。如果為null,就要默認類加載器
- interfaces: 這個新類要實現的接口組
- 調用處理器。
函數返回的對象類型是$Proxyn, (n >= 0. 第一次調用這個方法,新類名為$Proxy0, 第二個新類名為$Proxy1, 以此類推)
生成的$Proxyn 的源代碼大致類似如此:
public final class $Proxy0 implements interfaces {
InvocationHandler handler;
public String toString() {
Method m = this.getClass().getMethod("toString");
handler.invoke(this, m, m.getParameters());
}
public int hashCode() {
Method m = this.getClass().getMethod("hashCode");
handler.invoke(this, m, m.getParameters());
}
public String equals() {
Method m = this.getClass().getMethod("equals");
handler.invoke(this, m, m.getParameters());
}
// 以下是實現interfaces的方法
public return_type interfaces_method(args...) {
Method m = this.getClass().getMethod("equals");
handler.invoke(this, m, m.getParameters());
}
... ...接口interfaces中的其他方法
}
當我們這樣調用時: Object o = Proxy.newProxyInstance(null, interfaces, handler0);
就生成一個新$Proxy0類的對象o, 這個對象o的字段handler被賦值為handler0。$Proxy0實現了interfaces中所有的接口,其實現方式都一樣,就是調用字段handler的invoke方法。其UML圖如下:

posted on 2008-01-06 14:11
Jeff Lau 閱讀(1487)
評論(1) 編輯 收藏 所屬分類:
Jeff On Java 2008