proxy

1, Proxy提供了建立動態代理類和實例的靜態方法,也是建立動態代理方法的超類。函數

爲接口建立動態代理的步驟:spa

1 InvocationHandler handler = new MyInvocationHandler(...);
2 Class<?> proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(), Foo.class);
3 Foo f = (Foo) proxyClass.getConstructor(InvocationHandler.class).newInstance(handler);

一般咱們寫成這樣:代理

Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),new Class<?>[] { Foo.class },handler

動態代理類是在運行時實現了一系列的接口的類,code

代理接口;代理實例;handler對象

代理實例上調用的一個方法,會被傳遞給代理實例的handler,還有一堆參數對象,代理實例經過反射技術實現真正調用。blog

 

 

 

2,InvocationHandler是代理實例必須實現的接口接口

每一個代理實例都有一個調用處理函數handler,當代理實例產生方法調用時,實際就傳遞給代理實例的handler處理;get

 這個接口只有一個方法:io

Object invoke(Object proxy, Method method, Object[] args)throws Throwable

proxy 被代理的對象,method 代理對象調用的方法實例,class

相關文章
相關標籤/搜索