要想了解Java動態代理,首先要了解什麼叫做代理,熟悉設計模式的朋友一定知道在Gof總結的23種設計模式中,有一種叫做代理(Proxy)的對象結構型模式,動態代理中的代理,指的就是這種設計模式。
在java的動態代理機制中,有兩個重要的類或接口,一個是 InvocationHandler(Interface)、另一個則是 Proxy(Class),這一個類和接口是實現我們動態代理所必須用到的。首先我們先來看看java的API幫助文檔是怎麼樣對這兩個類進行描述的:
InvocationHandler:
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
一個動態代理的demo
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class HelloServiceProxy implements InvocationHandler {
private Object target;
/**
* 綁定委託對象並返回一個【代理佔位】
* @param target 真實對象
* @return 代理對象【佔位】
*/
public Object bind(Object target, Class[] interfaces) {
this.target = target;
//取得代理對象
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
@Override
/**
* 同過代理對象調用方法首先進入這個方法.
* @param proxy --代理對象
* @param method -- 方法,被調用方法.
* @param args -- 方法的參數
*/
public Object invoke(Object proxy , Method method, Object[] args) throws Throwable {
System.err.println("############我是JDK動態代理################");
Object result = null;
//反射方法前調用
System.err.println("我準備說hello。");
//反射執行方法 相當於調用target.sayHelllo;
result=method.invoke(target, args);
//反射方法後調用.
System.err.println("我說過hello了");
return result;
}
}
其中,bind方法中的newProxyInstanc方法,就是生成一個代理對象,第一個參數是類加載器,第二個參數是真實委託對象所實現的的接口(代理對象掛在那個接口下),第三個參數this代表當前HelloServiceProxy類,換句話說是使用HelloServiceProxy作為對象的代理。
尚學堂12大精英團隊+各類實戰項目,真正實現1+1>10的目標效果。幫助學員迅速成長,持久騰飛,成就學員“高富帥”人生;幫助企業技術和團隊成長,成就百年中華名企;助力中國持續成為世界強國而貢獻力量。尚學堂12大精英團隊,覆蓋IT行業十大領域,實戰團隊240人,服務學員累計超過10萬人,就業合作企業數量500+。
閱讀更多 Java的筆記 的文章