被谷歌解僱後,AI 倫理研究員米切爾加入人工智慧創業公司
阿新 • • 發佈:2021-08-25
Java動態代理機制的出現,使得 Java 開發人員不用手工編寫代理類,只要簡單地指定一組介面及委託類物件,便能動態地獲得代理類。代理類會負責將所有的方法呼叫分派到委託物件上反射執行,在分派執行的過程中,開發人員還可以按需調整委託類物件及其功能,這是一套非常靈活有彈性的代理框架。下面我們開始動態代理的學習。
動態代理的簡要說明
在java的動態代理機制中,有兩個重要的類或介面,一個是 InvocationHandler(Interface)、另一個則是 Proxy(Class)。
一、 InvocationHandler(interface)的描述:
InvocationHandler is the interface implemented by the invocation handler of a proxy instance. Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.
每一個動態代理類都必須要實現InvocationHandler這個介面,並且每個代理類的例項都關聯到了一個handler,當我們通過代理物件呼叫 一個方法的時候,這個方法的呼叫就會被轉發為由InvocationHandler這個介面的 invoke 方法來進行呼叫。我們來看看InvocationHandler這個介面的唯一一個方法invoke 方法:
Object invoke(Object proxy, Method method, Object[] args) throws Throwable
這個方法接收三個引數和返回一個Object型別,它們分別代表的意思如下:
- proxy: 指代我們所代理的那個真實物件
- method: 指代的是我們所要呼叫真實物件的方法的Method物件
- args: 指代的是呼叫真實物件某個方法時接受的引數
返回的Object是指真實物件方法的返回型別,以上會在接下來的例子中加以深入理解。
the value to return from the method invocation on the proxy instance.
二、 Proxy(Class)的描述:
Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
Proxy這個類的作用就是用來動態建立一個代理物件。我們經常使用的是newProxyInstance這個方法:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
引數的理解:
// 一個ClassLoader物件,定義了由哪個ClassLoader物件來對生成的代理物件進行載入 loader - the class loader to define the proxy class // 一個Interface物件的陣列,表示的是我將要給我需要代理的物件提供一組什麼介面 interfaces - the list of interfaces for the proxy class to implement // 一個InvocationHandler物件,表示的是當我這個動態代理物件在呼叫方法的時候,會關聯到哪一個InvocationHandler物件上 h - the invocation handler to dispatch method invocations to
返回結果的理解: 一個代理物件的例項
a proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and that implements the specified interfaces