1. 程式人生 > >動態代理類

動態代理類

//InvocationHandlerImpl 實現了InvocationHandler介面,並能實現方法呼叫從代理類到委託類的分派轉發
 //其內部通常包含指向委託類例項的引用,用於真正執行分派轉發過來的方法呼叫
InvocationHandler handler = new InvocaitonHandlerImpl(..);

//通過Proxy為包括Interface介面在內的一組介面動態建立代理類的物件
Class clazz = Proxy.getProxyClass(classLoader,new Class[]{Interface.class,...});

 //通過反射從生成的類物件獲得建構函式物件
 Constructor constructor = clazz.getConstructor(new Class[]{InvocationHandler.class});

 //通過建構函式物件建立動態代理類例項
Interface Proxy = (Interface)constructor.newInstance(new Object[]{handler});

 //Proxy類的靜態方法newProxyInstance對上面具體步驟的後三步做了封裝,簡化了動態代理物件的獲取過程。
 //InvocationHandlerImpl實現了InvocaitonHandler介面,並能實現方法呼叫從代理類到委託類的分派轉發
 InvocaitonHandler handler = new InvocationHandlerImpl(..);
 //通過Proxy直接建立動態代理類例項

 nterface proxy = (Interface)Proxy.newProxyInstance(classLoader,new Class[]{Interface.class