我們先來分析代理這個詞。 代理
代理是英文 Proxy 翻譯過來的。我們在生活中見到過的代理,大概最常見的就是朋友圈中賣面膜的同學了。
她們從廠家拿貨,然後在朋友圈中宣傳,然後賣給熟人。
按理說,顧客可以直接從廠家購買產品,但是現實生活中,很少有這樣的銷售模式。一般都是廠家委託給代理商進行銷售,顧客跟代理商打交道,而不直接與產品實際生產者進行關聯。
所以,代理就有一種中間人的味道。
接下來,我們說說軟體中的代理模式。 代理模式
代理模式是物件導向編程中比較常見的設計模式。
這是常見代理模式常見的 UML 示意圖。
需要注意的有下面幾點: 使用者只關心介面功能,而不在乎誰提供了功能。上圖中介面是 Subject。 介面真正實現者是上圖的 RealSubject,但是它不與使用者直接接觸,而是通過代理。 代理就是上圖中的 Proxy,由於它實現了 Subject 介面,所以它能夠直接與使用者接觸。 使用者調用 Proxy 的時候,Proxy 內部調用了 RealSubject。所以,Proxy 是中介者,它可以增強 RealSubject 操作。
如果難於理解的話,我用案例說明好了。值得注意的是,代理可以分為靜態代理和動態代理兩種。先從靜態代理講起。 靜態代理
我們平常去電影院看電影的時候,在電影開始的階段是不是經常會放廣告呢。
電影是電影公司委託給影院進行播放的,但是影院可以在播放電影的時候,產生一些自己的經濟收益,比如賣爆米花、可樂等,然後在影片開始結束時播放一些廣告。
現在用代碼來進行類比。
首先得有一個介面,通用的介面是代理模式實現的基礎。這個介面我們命名為 Movie,代表電影播放的能力。
package com.frank.test;public interface Movie { void play();}
然後,我們要有一個真正的實現這個 Movie 介面的類,和一個只是實現介面的代理類。
package com.frank.test;public class RealMovie implements Movie { @Override public void play() { // TODO Auto-generated method stub System.out.println("您正在觀看電影 《肖申克的救贖》"); }}
這個表示真正的影片。它實現了 Movie 介面,play() 方法調用時,影片就開始播放。那麼 Proxy 代理呢。
package com.frank.test;public class Cinema implements Movie { RealMovie movie; public Cinema(RealMovie movie) { super(); this.movie = movie; } @Override public void play() { guanggao(true); movie.play(); guanggao(false); } public void guanggao(boolean isStart){ if ( isStart ) { System.out.println("電影馬上開始了,爆米花、可樂、口香糖9.8折,快來買啊。"); } else { System.out.println("電影馬上結束了,爆米花、可樂、口香糖9.8折,買回家吃吧。"); } }}
Cinema 就是 Proxy 代理對象,它有一個 play() 方法。不過調用 play() 方法時,它進行了一些相關利益的處理,那就是廣告。現在,我們編寫測試代碼。
package com.frank.test;public class ProxyTest { public static void main(String[] args) { RealMovie realmovie = new RealMovie(); Movie movie = new Cinema(realmovie); movie.play(); }}
然後觀察結果:
電影馬上開始了,爆米花、可樂、口香糖9.8折,快來買啊。您正在觀看電影 《肖申克的救贖》電影馬上結束了,爆米花、可樂、口香糖9.8折,買回家吃吧。
現在可以看到,代理模式可以在不修改被代理對象的基礎上,通過擴充代理類,進行一些功能的附加與增強。值得注意的是,代理類和被代理類應該共同實現一個介面,或者是共同繼承某個類。
上面介紹的是靜態代理的內容,為什麼叫做靜態呢。因為它的類型是事先預定好的,比如上面代碼中的 Cinema 這個類。下面要介紹的內容就是動態代理。 動態代理
既然是代理,那麼它與靜態代理的功能與目的是沒有區別的,唯一有區別的就是動態與靜態差別。
那麼在動態代理的中這個動態體現在什麼地方。
上一節代碼中 Cinema 類是代理,我們需要手動編寫代碼讓 Cinema 實現 Movie 介面,而在動態代理中,我們可以讓程式在啟動並執行時候自動在記憶體中建立一個實現 Movie 介面的代理,而不需要去定義 Cinema 這個類。這就是它被稱為動態原因。
也許概念比較抽象。現在執行個體說明一下情況。
假設有一個大商場,商場有很多的櫃檯,有一個櫃檯賣茅台酒。我們進行代碼的類比。
package com.frank.test;public interface SellWine { void mainJiu();}
SellWine 是一個介面,你可以理解它為賣酒的許可證。
package com.frank.test;public class MaotaiJiu implements SellWine { @Override public void mainJiu() { // TODO Auto-generated method stub System.out.println("我賣得是茅台酒。"); }}
然後建立一個類 MaotaiJiu,對的,就是茅台酒的意思。
我們還需要一個櫃檯來賣酒:
package com.frank.test;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class GuitaiA implements InvocationHandler { private Object pingpai; public GuitaiA(Object pingpai) { this.pingpai = pingpai; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("銷售開始 櫃檯是: "+this.getClass().getSimpleName()); method.invoke(pingpai, args); System.out.println("銷售結束"); return null; }}
GuitaiA 實現了 InvocationHandler 這個類,這個類是什麼意思呢。大家不要慌張,待會我會解釋。
然後,我們就可以賣酒了。
package com.frank.test;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;public class Test { public static void main(String[] args) { // TODO Auto-generated method stub MaotaiJiu maotaijiu = new MaotaiJiu(); InvocationHandler jingxiao1 = new GuitaiA(maotaijiu); SellWine dynamicProxy = (SellWine) Proxy.newProxyInstance(MaotaiJiu.class.getClassLoader(), MaotaiJiu.class.getInterfaces(), jingxiao1); dynamicProxy.mainJiu(); }}
這裡,我們又接觸到了一個新的概念,沒有關係,先別管,先看結果。
銷售開始 櫃檯是: GuitaiA我賣得是茅台酒。銷售結束
看到沒有,我並沒有像靜態代理那樣為 SellWine 介面實現一個代理類,但最終它仍然實現了相同的功能,這其中的差別,就是之前討論的動態代理所謂“動態”的原因。 動態代理文法
放輕鬆,下面我們開始講解文法,文法非常簡單。
動態代碼涉及了一個非常重要的類 Proxy。正是通過 Proxy 的靜態方法 newProxyInstance 才會動態建立代理。 Proxy
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
下面講解它的 3 個參數意義。 loader 自然是類載入器 interfaces 代碼要用來代理的介面 h 一個 InvocationHandler 對象
初學者應該對於 InvocationHandler 很陌生,我馬上就講到這一塊。 InvocationHandler
InvocationHandler 是一個介面,官方文檔解釋說,每個代理的執行個體都有一個與之關聯的 InvocationHandler 實作類別,如果代理的方法被調用,那麼代理便會通知和轉寄給內部的 InvocationHandler 實作類別,由它決定處理。
public interface InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable;}
InvocationHandler 內部只是一個 invoke() 方法,正是這個方法決定了怎麼樣處理代理傳遞過來的方法調用。 proxy 代理對象 method 代理對象調用的方法 args 調用的方法中的參數
因為,Proxy 動態產生的代理會調用 InvocationHandler 實作類別,所以 InvocationHandler 是實際執行者。
public class GuitaiA implements InvocationHandler { private Object pingpai; public GuitaiA(Object pingpai) { this.pingpai = pingpai; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("銷售開始 櫃檯是: "+this.getClass().getSimpleName()); method.invoke(pingpai, args); System.out.println("銷售結束"); return null; }}
GuitaiA 就是實際上賣酒的地方。
現在,我們加大難度,我們不僅要賣茅台酒,還想賣五糧液。
package com.frank.test;public class Wuliangye implements SellWine { @Override public void mainJiu() { // TODO Auto-generated method stub System.out.println("我賣得是五糧液。"); }}
Wuliangye 這個類也實現了 SellWine 這個介面,說明它也擁有賣酒的許可證,同樣把它放到 GuitaiA 上售賣。
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub MaotaiJiu maotaijiu = new MaotaiJiu(); Wuliangye wu = new Wuliangye(); InvocationHandler jingxiao1 = new GuitaiA(maotaijiu); InvocationHandler jingxiao2 = new GuitaiA(wu); SellWine dynamicProxy = (SellWine) Proxy.newProxyInstance(MaotaiJiu.class.getClassLoader(), MaotaiJiu.class.getInterfaces(), jingxiao1); SellWine dynamicProxy1 = (SellWine) Proxy.newProxyInstance(MaotaiJiu.class.getClassLoader(), MaotaiJiu.class.getInterfaces(), jingxiao2); dynamicProxy.mainJiu(); dynamicProxy1.mainJiu(); }}
我們來看結果:
銷售開始 櫃檯是: GuitaiA我賣得是茅台酒。銷售結束銷售開始 櫃檯是: GuitaiA我賣得是五糧液。銷售結束
有人會問,dynamicProxy 和 dynamicProxy1 什麼區別沒有。他們都是動態產生的代理,都是售貨員,都擁有賣酒的技術認證。
我現在擴大商場的經營,除了賣酒之外,還要賣煙。
首先,同樣要建立一個介面,作為賣煙的許可證。
package com.frank.test;public interface SellCigarette { void sell();}
然後,賣什麼煙呢。我是湖南人,那就芙蓉王好了。
public class Furongwang implements SellCigarette { @Override public void sell() { // TODO Auto-generated method stub System.out.println("售賣的是正宗的芙蓉王,可以掃描條碼查證。"); }}
然後再次測實驗證:
package com.frank.test;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Proxy;public class Test { public static void main(String[] args) { // TODO Auto-generated method stub MaotaiJiu maotaijiu = new MaotaiJiu(); Wuliangye wu = new Wuliangye(); Furongwang fu = new Furongwang(); InvocationHandler jingxiao1 = new GuitaiA(maotaijiu); InvocationHandler jingxiao2 = new GuitaiA(wu); InvocationHandler jingxiao3 = new GuitaiA(fu); SellWine dynamicProxy = (SellWine) Proxy.newProxyInstance(MaotaiJiu.class.getClassLoader(), MaotaiJiu.class.getInterfaces(), jingxiao1); SellWine dynamicProxy1 = (SellWine) Proxy.newProxyInstance(MaotaiJiu.class.getClassLoader(), MaotaiJiu.class.getInterfaces(), jingxiao2); dynamicProxy.mainJiu(); dynamicProxy1.mainJiu(); SellCigarette dynamicProxy3 = (SellCigarette) Proxy.newProxyInstance(Furongwang.class.getClassLoader(), Furongwang.class.getInterfaces(), jingxiao3); dynamicProxy3.sell(); }}
然後,查看結果:
銷售開始 櫃檯是: GuitaiA我賣得是茅台酒。銷售結束銷售開始 櫃檯是: GuitaiA我賣得是五糧液。銷售結束銷售開始 櫃檯是: GuitaiA售賣的是正宗的芙蓉王,可以掃描條碼查證。銷售結束
結果符合預期。大家仔細觀察一下代碼,同樣是通過 Proxy.newProxyInstance() 方法,卻產生了 SellWine 和 SellCigarette 兩種介面的實作類別代理,這就是動態代理的魔力。 動態代理的秘密
一定有同學對於為什麼 Proxy 能夠動態產生不同介面類型的代理感興趣,我的猜測是肯定通過傳入進去的介面然後通過反射動態產生了一個介面執行個體。
比如 SellWine 是一個介面,那麼 Proxy.newProxyInstance() 內部肯定會有
new SellWine();
這樣相同作用的代碼,不過它是通過反射機制建立的。那麼事實是不是這樣子呢。直接查看它們的源碼好了。需要說明的是,我當前查看的源碼是 1.8 版本。
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException { Objects.requireNonNull(h); final Class<?>[] intfs = interfaces.clone(); /* * Look up or generate the designated proxy class. */ Class<?> cl = getProxyClass0(loader, intfs); /* * Invoke its constructor with the designated invocation handler. */ try { final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { cons.setAccessible(true); return null; } }); } return cons.newInstance(new Object[]{h}); } catch (IllegalAccessException|InstantiationException e) { throw new InternalError(e.toString(), e); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { throw new InternalError(t.toString(), t); } } catch (NoSuchMethodException e) { throw new InternalError(e.toString(), e); } }
newProxyInstance 的確建立了一個執行個體,它是通過 cl 這個 Class 檔案的構造方法反射產生。cl 由 getProxyClass0() 方法擷取。
private static Class<?> getProxyClass0(ClassLoader loader, Class<?>... interfaces) { if (interfaces.length > 65535) { throw new IllegalArgumentException("interface limit exceeded"); } // If the proxy class defined by the given loader implementing // the given interfaces exists, this will simply return the cached copy; // otherwise, it will create the proxy class via the ProxyClassFactory return proxyClassCache.get(loader, interfaces);}
直接通過緩衝擷取,如果擷取不到,注釋說會通過 ProxyClassFactory 產生。
/** * A factory function that generates, defines and returns the proxy class given * the ClassLoader and array of interfaces. */ private static final class ProxyClassFactory implements BiFunction<ClassLoader, Class<?>[], Class<?>> { // Proxy class 的首碼是 “$Proxy”, private static final String proxyClassNamePrefix = "$Proxy"; // next number to use for generation of unique proxy class names private static final AtomicLong nextUniqueNumber = new AtomicLong(); @Override public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) { Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length); for (Class<?> intf : interfaces) { /* * Verify that the class loader resolves the name of this * interface to the same Class object. */ Class<?> interfaceClass = null; try { interfaceClass = Class.forName(intf.getName(), false, loader); } catch (ClassNotFoundException e) { } if (interfaceClass != intf) { throw new IllegalArgumentException( intf + " is not visible from class loader"); } /* * Verify that the Class object actually represents an * interface. */ if (!interfaceClass.isInterface()) { throw new IllegalArgumentException( interfaceClass.getName() + " is not an interface"); } /* * Verify that this interface is not a duplicate. */ if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { throw new IllegalArgumentException( "repeated interface: " + interfaceClass.getName()); } } String proxyPkg = null; // package to define proxy class in int accessFlags = Modifier.PUBLIC | Modifier.FINAL; /* * Record the package of a non-public proxy interface so that the * proxy class will be defined in the same package. Verify that * all non-public proxy interfaces are in the same package. */ for (Class<?> intf : interfaces) { int flags = intf.getModifiers(); if (!Modifier.isPublic(flags)) { accessFlags = Modifier.FINAL; String name = intf.getName(); int n = name.lastIndexOf('.'); String pkg = ((n == -1) ? "" : name.substring(0, n + 1)); if (proxyPkg == null) { proxyPkg = pkg; } else if (!pkg.equals(proxyPkg)) { throw new IllegalArgumentException( "non-public interfaces from different packages"); } } } if (proxyPkg == null) { // if no non-public proxy interfaces, use com.sun.proxy package proxyPkg = ReflectUtil.PROXY_PACKAGE + "."; } /* * Choose a name for the proxy class to generate. */ long num = nextUniqueNumber.getAndIncrement(); String proxyName = proxyPkg + proxyClassNamePrefix + num; /* * Generate the specified proxy class. */ byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags); try { return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length); } catch (ClassFormatError e) { /* * A ClassFormatError here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded). */ throw new IllegalArgumentException(e.toString()); } } }
這個類的注釋說,通過指定的 ClassLoader 和 介面數組 用Factory 方法產生 proxy class。 然後這個 proxy class 的名字是:
// Proxy class 的首碼是 “$Proxy”,private static final String proxyClassNamePrefix = "$Proxy";long num = nextUniqueNumber.getAndIncrement();String proxyName = proxyPkg + proxyClassNamePrefix + nu
所以,動態產生的代理類名稱是包名+$Proxy+id序號。
產生的過程,核心代碼如下:
byte[] proxyClassFile = ProxyGenerator.generateProxyClass( proxyName, interfaces, accessFlags);return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length)
這兩個方法,我沒有繼續追蹤下去,defineClass0() 甚至是一個 native 方法。我們只要知道,動態建立代理這回事就好了。
現在我們還需要做一些驗證,我要檢測一下動態產生的代理類的名字是不是包名+$Proxy+id序號。
public class Test { public static void main(String[] args) { // TODO Auto-generated method stub MaotaiJiu maotaijiu = new MaotaiJiu(); Wuliangye wu = new Wuliangye(); Furongwang fu = new Furongwang(); InvocationHandler jingxiao1 = new GuitaiA(maotaijiu); InvocationHandler jingxiao2 = new GuitaiA(wu); InvocationHandler jingxiao3 = new GuitaiA(fu); SellWine dynamicProxy = (SellWine) Proxy.newProxyInstance(MaotaiJiu.class.getClassLoader(), MaotaiJiu.class.getInterfaces(), jingxiao1); SellWine dynamicProxy1 = (SellWine) Proxy.newProxyInstance(MaotaiJiu.class.getClassLoader(), MaotaiJiu.class.getInterfaces(), jingxiao2); dynamicProxy.mainJiu(); dynamicProxy1