一文說透"靜態代理"與"動態代理"

{"type":"doc","content":[{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"追溯"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"學一個技術,要知道技術因何而產生,纔能有學下去的目標和動力,才能更好的理解"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"首先,要明確爲什麼要存在"},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong"}],"text":"代理"}],"marks":[{"type":"strong"}]},{"type":"text","marks":[{"type":"strong"}],"text":"呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"存在一個常見的需求:"},{"type":"codeinline","content":[{"type":"text","text":"怎樣在不修改類A代碼的情況下,在調用類A的方法時進行一些功能的附加與增強呢? "}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"先不考慮什麼代理不代理的,我們設計一個簡單的實現方案:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"新創建一個類B,類B組合類A,在類B中創建一個方法b,方法b中調用類A中的方法a,在調用前和調用後都可以添加一些自定義的附加與增強代碼。 當有需求需要調用類A的方法a並且想要添加一個附加功能時,就去調用類B的方法b即可實現上述需求;"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面爲了便於理解,附上僞代碼:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"// 定義類A\npublic class ClassA{\n public void methoda(){\n System.out.println(\"我是方法a!\");\n }\n}\n\n// 定義類B\npublic class ClassB{\n // 組合ClassA\n ClassA A;\n public ClassB(ClassA A){\n this.A = A;\n }\n \n @Override\n public void methodb(){\n System.out.println(\"我是方法a的附加功能代碼,我執行啦~!\");\n A.methoda();\n System.out.println(\"我是方法a的附加功能代碼,我完成啦~!\");\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面,讓我們來調用一下ClassB的methodb方法,則會產生以下輸出:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"我是方法a的附加功能代碼,我執行啦~!\n我是方法a!\n我是方法a的附加功能代碼,我完成啦~!"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"可以發現,方法a執行了,並且在沒有修改類A代碼的前提下,爲方法a附加了其他的功能;"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"不難吧,其實上述的代碼就是一個最簡單的"},{"type":"codeinline","content":[{"type":"text","text":"代理模式"}]},{"type":"text","text":"了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"代理存在的意義"},{"type":"text","text":":使用代理模式可以在不修改別代理對象代碼的基礎上,通過擴展代理類,進行一些功能的附加與增強"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":1},"content":[{"type":"text","text":"代理種類"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"代理分爲"},{"type":"codeinline","content":[{"type":"text","text":"靜態代理"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"動態代理"}]},{"type":"text","text":",其涉及的設計模式就是"},{"type":"codeinline","content":[{"type":"text","text":"代理模式"}]},{"type":"text","text":"本尊了,代理模式一般包含幾種元素,如下圖:"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/88/886b17a559613e5b9c589f3427027642.png","alt":"在這裏插入圖片描述","title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"主題接口(subject):定義代理類和真實主題的公共對外方法,也是代理類代理真實主題的方法;"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"真實主題(RealSubject):真正實現業務邏輯的類;"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"代理類(Proxy):用來代理和封裝真實主題;"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"客戶端(Client):使用代理類和主題接口完成一些工作。 "}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"爲了更好的理解,我們將上述實現的最簡易版的代理完善一下,添加接口,代理類也實現相應的被代理類的接口,實現同一個方法,僞代碼如下:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"// 被代理類的接口(上圖中subject)\npublic interface ImpA{\n void methoda();\n}\n// 定義類A(上圖中RealSubject)\npublic class ClassA implements ImpA{\n public void methoda(){\n System.out.println(\"我是方法a!\");\n }\n}\n\n// 定義類B(上圖中Proxy)\npublic class ClassB implements ImpA {\n // 組合ClassA\n ImpA A;\n public ClassB(ClassA A){\n this.A = A;\n }\n \n // 重寫被代理類的方法\n @Override\n public void methoda(){\n System.out.println(\"我是方法a的附加功能代碼,我執行啦~!\");\n A.methoda();\n System.out.println(\"我是方法a的附加功能代碼,我完成啦~!\");\n }\n}\n// 客戶端類(上圖中Client)\npublic class Main{\n // 創建被代理對象實例\n ImpA A = new ClassA();\n // 構造器注入被代理對象實例\n ImpA B = new ClassB(A);\n // 調用代理方法\n B.methoda();\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"靜態代理"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"所謂靜態代理也就是在程序運行前就已經存在代理類的字節碼文件,代理類和委託類的關係在運行前就確定了。"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面的代碼就是實現了一個靜態代理; 其實靜態代理就已經能夠滿足上述需求了,爲什麼還需要動態代理呢? 這裏就涉及到靜態代理的兩個缺點了"}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"代理對象"}]},{"type":"text","text":"的一個接口只服務於一種類型的對象,如果要代理的方法很多,勢必要爲每一種方法都進行代理,在程序規模稍大時靜態代理代理類就會過多會造成代碼混亂"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"如果接口增加一個方法,除了所有實現類需要實現這個方法外,所有代理類也需要實現此方法,增加了代碼維護的複雜度。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"基於上述兩個問題,動態代理誕生了~"}]},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"動態代理"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"動態代理是在程序運行時,通過反射獲取被代理類的字節碼內容用來創建代理類"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"具體什麼是動態代理呢?"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"名詞:"},{"type":"codeinline","content":[{"type":"text","text":"動態"}]},{"type":"text","text":",動態在程序中就是表達在程序運行時就根據配置自動的生成代理類並且代理類和被代理類是在運行時才確定相互之間的關係;"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在JDK中包含兩種動態代理的實現機制:"},{"type":"codeinline","content":[{"type":"text","text":"JDK Proxy"}]},{"type":"text","text":" 和 "},{"type":"codeinline","content":[{"type":"text","text":"CGLib"}]},{"type":"text","text":";"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面我們以"},{"type":"codeinline","content":[{"type":"text","text":"JDK Proxy"}]},{"type":"text","text":"爲例,講解一下動態代理和根據源碼分析並簡單說一下應用場景"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"JDK Proxy"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"JDK Proxy動態代理"}]},{"type":"text","text":",api在包"},{"type":"codeinline","content":[{"type":"text","text":"java.lang.reflect"}]},{"type":"text","text":"下,大家可能發現了,爲什麼在反射的包下呢?這個問題我們下面的源碼分析會解決;"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"其核心api包含兩個重要的核心接口和類:一個是 "},{"type":"codeinline","content":[{"type":"text","text":"InvocationHandler(Interface)"}]},{"type":"text","text":"、另一個則是 "},{"type":"codeinline","content":[{"type":"text","text":"Proxy(Class)"}]},{"type":"text","text":",簡單說就這兩個簡單的很,這兩個是我們實現動態代理所必需的用到的,下面簡單介紹一下兩個類:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"java.lang.reflect.Proxy(Class)"}]},{"type":"text","text":" :Proxy是 Java 動態代理機制的主類,提供一組靜態方法來爲一組接口動態地生成代理類及其對象。包含以下四個靜態方法:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"static InvocationHandler getInvocationHandler(Object proxy)"}]}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"該方法用於獲取指定代理對象所關聯的調用處理器"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"static Class getProxyClass(ClassLoader loader, Class[] interfaces)"}]}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"該方法用於獲取關聯於指定類裝載器和一組接口的動態代理類的類對象"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"static boolean isProxyClass(Class cl)"}]}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"該方法用於判斷指定類對象是否是一個動態代理類"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"static Object newProxyInstance(ClassLoader loader, Class[] interfaces,InvocationHandler h)"}]}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"該方法用於爲指定類裝載器、一組接口及調用處理器生成動態代理類實例,包含下面的參數:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" * "},{"type":"codeinline","content":[{"type":"text","text":"loader"}]},{"type":"text","text":" 指定代理類的ClassLoader加載器"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" * "},{"type":"codeinline","content":[{"type":"text","text":"interfaces"}]},{"type":"text","text":" 指定代理類要實現的所有接口"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":" * "},{"type":"codeinline","content":[{"type":"text","text":"h"}]},{"type":"text","text":": 表示的是當這個動態代理對象在調用方法的時候,會關聯到哪一個InvocationHandler對象上"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"該方法用於爲指定類裝載器、一組接口及調用處理器生成動態代理類實例"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"java.lang.reflect.InvocationHandler(interface)"}]},{"type":"text","text":" : "},{"type":"codeinline","content":[{"type":"text","text":"InvocationHandler"}]},{"type":"text","text":"是上述"},{"type":"codeinline","content":[{"type":"text","text":"newProxyInstance"}]},{"type":"text","text":"方法的"},{"type":"codeinline","content":[{"type":"text","text":"InvocationHandler h"}]},{"type":"text","text":"參數傳入,負責連接代理類和委託類的中間類必須實現的接口"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"它自定義了一個 invoke 方法,用於集中處理在動態代理類對象上的方法調用,通常在該方法中實現對委託類的代理訪問。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"上述就是動態代理兩個核心的方法,不太明白?先別急,我們先用上述實現一個動態代理,你先看一下"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"還是以上述的案例從靜態代理來改造爲動態代理,實現動態代理主要就兩步,假設還是存在上述的ImplA、ClassA"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"1:創建一個"},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong"}],"text":"處理器"}],"marks":[{"type":"strong"}]},{"type":"text","marks":[{"type":"strong"}],"text":"類實現InvocationHandler接口,重寫invoke方法,僞代碼如下:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public class MyHandler implements InvocationHandler{\n // 標識被代理類的實例對象\n private Object delegate; \n // 構造器注入被代理對象\n public MyHandler(Object delegate){\n this.delegate = delegate;\n }\n \n // 重寫invoke方法\n @Override\n public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {\n System.out.println(\"被代理方法調用前的附加代碼執行~ \");\n // 真實的被代理方法調用\n method.invoke(delegate, args);\n System.out.println(\"被代理方法調用後的附加代碼執行~ \");\n } \n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好了,這樣一個"},{"type":"codeinline","content":[{"type":"text","text":"處理器"}]},{"type":"text","text":"就搞定了,當我們在調用"},{"type":"codeinline","content":[{"type":"text","text":"被代理類"}]},{"type":"text","text":"的方法時,就是去執行上述"},{"type":"codeinline","content":[{"type":"text","text":"重寫的invoke方法"}]},{"type":"text","text":",下面創建一個ClassA的"},{"type":"codeinline","content":[{"type":"text","text":"代理類"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"**2:創建"},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong"}],"text":"代理類"}],"marks":[{"type":"strong"}]},{"type":"text","marks":[{"type":"strong"}],"text":",並調用被代理方法**"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public class MainTest{\n public static void main(String[] args) { \n // 創建被代理對象\n ImplA A = new ClassA();\n // 創建處理器類實現\n InvocationHandler myHandler = new MyHandler(A);\n // 重點! 生成代理類, 其中proxyA就是A的代理類了\n ImplA proxyA = (ImplA)Proxy.newProxyInstance(A.getClass().getClassLoader(), A.getClass().getInterfaces(), myHandler);\n // 調用代理類的代理的methoda方法, 在此處就會去調用上述myHandler的invoke方法區執行,至於爲什麼,先留着疑問,下面會說清楚~\n proxyA.methoda();\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好了,至此一個動態代理就構建完成了,執行代碼,會發現輸出:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"被代理方法調用前的附加代碼執行~\n我是方法a!\n被代理方法調用後的附加代碼執行~"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"太簡單了有木有,這裏總結一下動態代理的優缺點:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"優點:"}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"動態代理類不僅簡化了編程工作,而且提高了軟件系統的可擴展性,因爲Java 反射機制可以生成任意類型的動態代理類。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"2","normalizeStart":"2"},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"動態代理類的字節碼在程序運行時由Java反射機制動態生成,無需程序員手工編寫它的源代碼。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"numberedlist","attrs":{"start":"3","normalizeStart":"3"},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"接口增加一個方法,除了所有實現類需要實現這個方法外,動態代理類會直接自動生成對應的代理方法。"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"缺點:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"JDK proxy只能對有實現接口的類才能代理,也就是說沒有接口實現的類,jdk proxy是無法代理的,爲什麼呢?下面會解答."}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"}],"text":"有什麼解決方案嗎?"},{"type":"text","text":" 當然有,還有一種動態代理的方案:"},{"type":"codeinline","content":[{"type":"text","text":"CGLib"}]},{"type":"text","text":",它是針對類實現代理,主要是對指定的類生成一個子類,覆蓋其中的方法,並覆蓋其中方法實現增強,但是因爲採用的是繼承,所以該類或方法最好不要聲明成final,對於final類或方法,是無法繼承的,和jdk proxy基本思想是相似的,畢竟都是動態代理的實現方案嘛,在這篇文章就不做詳解了,博主會在其他的博文單獨介紹這個nb的框架"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"上述帶大家搞了一遍動態代理和靜態代理的應用;在這過程中,你有沒有想過,動態代理是怎麼實現的呢?"},{"type":"text","text":" "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"下面我們就從源碼的角度分析一下,解決大家的疑問。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"源碼分析"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在開始分析的時候,我希望大家帶着幾個"},{"type":"codeinline","content":[{"type":"text","text":"問題"}]},{"type":"text","text":"去閱讀,可以幫助大家更好的理解:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"問題1"}]},{"type":"text","text":":代理類爲什麼可以在運行的時候自動生成呢?如何生成的呢?"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"問題2"}]},{"type":"text","text":":爲什麼調用代理類的相應的代理方法就可以調用到InvocationHandler實現類的invoke方法呢?"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"問題3"}]},{"type":"text","text":":爲什麼jdk proxy只支持代理有接口實現的類呢?"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"ps :"},{"type":"text","marks":[{"type":"italic"}],"text":"爲了提升閱讀體驗,讓大家有一個更清晰的認知,以下源碼會將一些異常處理和日誌打印代碼刪除,只保留主幹代碼,請知悉~"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們就從兩個核心:"},{"type":"codeinline","content":[{"type":"text","text":"InvocationHandler"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"Proxy"}]},{"type":"text","text":"來進行分析整個脈絡,他們都在"},{"type":"codeinline","content":[{"type":"text","text":"java.lang.reflect"}]},{"type":"text","text":"包下"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"InvocationHandler源碼"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public interface InvocationHandler {\n public Object invoke(Object proxy, Method method, Object[] args)\n throws Throwable;\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上述就是InvocationHandler的源碼,沒什麼其他的就是一個接口,裏面有一個待實現方法invoke,處理類實現此接口重寫invoke方法"}]},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"Proxy源碼"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"public class Proxy implements java.io.Serializable {\n // 處理類實例 變量\n protected InvocationHandler h;\n // 用於存儲 已經通過動態代理獲取過的代理類緩存\n private static final WeakCache[], Class>> proxyClassCache = new WeakCache<>(new KeyFactory(),new ProxyClassFactory());\n // 私有無參構造,使得只能通過傳入InvocationHandler參數來創建該對象\n private Proxy() {}\n // 保護 構造函數,入參InvocationHandler處理類\n protected Proxy(InvocationHandler h) {\n Objects.requireNonNull(h);\n this.h = h;\n }\n public static Class> getProxyClass(ClassLoader loader,Class>... interfaces) throws IllegalArgumentException{\n ...\n }\n public static boolean isProxyClass(Class> cl) {\n ...\n }\n public static InvocationHandler getInvocationHandler(Object proxy) throws IllegalArgumentException {\n ...\n }\n // 生成代理類的實現方法\n public static Object newProxyInstance(ClassLoader loader,Class>[] interfaces,InvocationHandler h) throws IllegalArgumentException{\n ...\n\t}\n // 各種私有方法\n private ... ...\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"Proxy"}]},{"type":"text","text":"類的整體的架構就類似於上述,"},{"type":"codeinline","content":[{"type":"text","text":"InvocationHandler h"}]},{"type":"text","text":"參數和"},{"type":"codeinline","content":[{"type":"text","text":"兩個構造函數"}]},{"type":"text","text":"、"},{"type":"codeinline","content":[{"type":"text","text":"四個上述已經介紹過的共有方法"}]},{"type":"text","text":",還有一系列的私有方法,getProxyClass、isProxyClass、getInvocationHandler功能就和上面介紹的一樣,就不再詳細介紹了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"**我們下面來主要看一下"},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong"}],"text":"newProxyInstance"}],"marks":[{"type":"strong"}]},{"type":"text","marks":[{"type":"strong"}],"text":"方法**"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"newProxyInstance方法,我在方法內添加上了對應的註釋:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":" public static Object newProxyInstance(ClassLoader loader, Class>[] interfaces, InvocationHandler h) throws IllegalArgumentException{\n // 1. 克隆對應的接口,用於代理類實現的接口數組\n final Class>[] intfs = interfaces.clone();\n ...\n /*\n * Look up or generate the designated proxy class. 源碼中的介紹\n * 2. 查找或者生成指定的代理類, 下面會詳細介紹\n */\n Class> cl = getProxyClass0(loader, intfs);\n /*\n * Invoke its constructor with the designated invocation handler.\n * 3. 上面代碼已經生成了代理類 cl,cl其中包含一個參數爲傳入的InvocationHandler h的構造函數, 獲取該構造函數並通過該構造函數創建一個類的實例對象並返回\n */\n try {\n // 4. 通過《反射》獲取參數爲InvocationHandler的構造函數\n final Constructor> cons = cl.getConstructor(constructorParams);\n final InvocationHandler ih = h;\n // 5. 判斷構造函數是否爲私有的,如果爲私有的則需要設置私有可訪問權限\n if (!Modifier.isPublic(cl.getModifiers())) {\n AccessController.doPrivileged(new PrivilegedAction() {\n public Void run() {\n cons.setAccessible(true);\n return null;\n }\n });\n }\n // 6. 通過上述獲取的構造函數創建對應的 實例對象,並返回!over~\n return cons.newInstance(new Object[]{h});\n } catch (IllegalAccessException|InstantiationException e) {\n // 各種異常處理\n }\n }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在上面的代碼中,我簡單的標註了一下每行代碼的作用,下面我們來詳細分析一下;"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"代理類的字節碼生成邏輯"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們知道,在加載jvm前,java文件都已經被編譯成了"},{"type":"codeinline","content":[{"type":"text","text":"class字節碼"}]},{"type":"text","text":"文件, 然後jvm通過"},{"type":"codeinline","content":[{"type":"text","text":"類加載器"}]},{"type":"text","text":"將字節碼文件加載到jvm中;"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們的代理類也是這樣,不同的是動態代理的類是在程序運行時產生的,我們要做的就是如何在程序運行的時候,通過"},{"type":"codeinline","content":[{"type":"text","text":"被代理類"}]},{"type":"text","text":"的字節碼生成"},{"type":"codeinline","content":[{"type":"text","text":"代理類"}]},{"type":"text","text":"的字節碼!"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"我們接下來詳細分析"},{"type":"codeinline","content":[{"type":"text","text":"newProxyInstance"}]},{"type":"text","text":"方法:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在newProxyInstance中調用了"},{"type":"codeinline","content":[{"type":"text","text":"Class> cl = getProxyClass0(loader, intfs);"}]},{"type":"text","text":"語句生成了"},{"type":"codeinline","content":[{"type":"text","text":"代理類的字節碼"}]},{"type":"text","text":",此處調用了getProxyClass0方法,傳入了指定的類加載器和對應要實現的接口"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"那麼, 我們看看"},{"type":"codeinline","content":[{"type":"text","text":"getProxyClass0"}]},{"type":"text","text":"方法的實現:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":" private static Class> getProxyClass0(ClassLoader loader, Class>... interfaces) {\n if (interfaces.length > 65535) {\n throw new IllegalArgumentException(\"interface limit exceeded\");\n }\n // proxyClassCache是WeakCache弱引用緩存類,如果之前就生成過對應的代理類就從緩存中取,如果沒生成過就重新生成\n return proxyClassCache.get(loader, interfaces);\n }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"codeinline","content":[{"type":"text","text":"proxyClassCache"}]},{"type":"text","text":"是Proxy類中的靜態變量,是WeakCache類,裏面封裝了兩個類KeyFactory、ProxyClassFactory,都是BiFunction函數式接口(如果不清楚函數式接口,請自行google);"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"將其拿過來看一下"},{"type":"codeinline","content":[{"type":"text","text":"proxyClassCache = new WeakCache<>(new KeyFactory(),new ProxyClassFactory());"}]},{"type":"text","text":" 其中調用了proxyClassCache.get(loader, interfaces)方法的實現"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"未避免代碼過長,只粘貼了核心代碼:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":" public V get(K key, P parameter) {\n ...\n // 這部分主要是獲取對應的 函數式接口,如果不明白函數式接口,google一下吧~\n Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));\n Supplier supplier = valuesMap.get(subKey);\n Factory factory = null;\n while (true) { // 此處爲什麼是while循環呢, 主要是supplier不爲空的話,則執行下面的語句賦值後,再循環執行下一次則supplier不爲空\n if (supplier != null) {\n // 如果存在對應的函數式接口, 調用函數式接口對應的代碼\n // 重點!!!調用函數式接口!!\n V value = supplier.get();\n if (value != null) {\n return value;\n }\n }\n if (factory == null) {\n // 創建一個 專門創建代理類字節碼的工廠類,實現類是ProxyClassFactory\n factory = new Factory(key, parameter, subKey, valuesMap);\n }\n if (supplier == null) {\n supplier = valuesMap.putIfAbsent(subKey, factory);\n if (supplier == null) {\n // 將supplier賦值factory\n supplier = factory;\n }}}} }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"總結一下上述方法的流程:"}]},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/dd/dd4075e770f22de66a4ed95a6bf08255.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"接着"},{"type":"codeinline","content":[{"type":"text","text":"ProxyClassFactory.apply"}]},{"type":"text","text":"方法看一下:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":" public Class> apply(ClassLoader loader, Class>[] interfaces) {\n Map, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);\n // 獲取接口對應的接口class對象\n for (Class> intf : interfaces) {\n Class> interfaceClass = null;\n try {\n interfaceClass = Class.forName(intf.getName(), false, loader);\n } \n if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) { }\n }\n\n String proxyPkg = null;\n int accessFlags = Modifier.PUBLIC | Modifier.FINAL;\n // 判斷是否包含公有的接口對象,判斷是否可以通過jdk proxy的方式進行生成代理類\n for (Class> intf : interfaces) {\n int flags = intf.getModifiers();\n if (!Modifier.isPublic(flags)) {\n accessFlags = Modifier.FINAL;\n String name = intf.getName();\n int n = name.lastIndexOf('.');\n String pkg = ((n == -1) ? \"\" : name.substring(0, n + 1));\n if (proxyPkg == null) {\n proxyPkg = pkg;\n } else if (!pkg.equals(proxyPkg)) {\n }\n }\n }\n // 如果沒有公有接口類,需要使用CGLib來實現。。。\n if (proxyPkg == null) {\n proxyPkg = ReflectUtil.PROXY_PACKAGE + \".\";\n }\n // 組裝代理類的類名稱\n long num = nextUniqueNumber.getAndIncrement();\n String proxyName = proxyPkg + proxyClassNamePrefix + num;\n // 重點!! 此處生成代理類的字節碼數組\n byte[] proxyClassFile = ProxyGenerator.generateProxyClassproxyName, interfaces, accessFlags);\n try {\n // 通過類加載器將字節碼數組加載到JVm的方法區中生成Class對象!\n return defineClass0(loader, proxyName,\n proxyClassFile, 0, proxyClassFile.length);\n } catch (ClassFormatError e) {\n }\n }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上述的"},{"type":"codeinline","content":[{"type":"text","text":" byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces, accessFlags);"}]},{"type":"text","text":" 爲生成代理類字節碼數組的方法,調用的方法中調用了"},{"type":"codeinline","content":[{"type":"text","text":"generateClassFile"}]},{"type":"text","text":"方法;"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"private byte[] generateClassFile() {\n // 首先,默認代理的三個方法:hashCode\\equals\\toString\n this.addProxyMethod(hashCodeMethod, Object.class);\n this.addProxyMethod(equalsMethod, Object.class);\n this.addProxyMethod(toStringMethod, Object.class);\n // 獲取所有的要被代理類實現的接口\n Class[] var1 = this.interfaces;\n int var2 = var1.length;\n int var3;\n Class var4;\n // 遍歷上述獲取的接口\n for(var3 = 0; var3 < var2; ++var3) {\n // 賦值: 將接口的Class對象賦值!\n var4 = var1[var3];\n // 通過“反射”獲取所有方法\n Method[] var5 = var4.getMethods();\n int var6 = var5.length;\n\n for(int var7 = 0; var7 < var6; ++var7) {\n Method var8 = var5[var7];\n // 將方法添加到 要被代理的方法中\n this.addProxyMethod(var8, var4);\n }\n }\n // 獲取要代理方法後,開始組裝字節碼\n var14.writeInt(-889275714);\n var14.writeShort(0);\n var14.writeShort(this.accessFlags);\n var14.writeShort(this.cp.getClass(dotToSlash(this.className)));\n // 注意!!! .... 此處省略了絕大部分 字節碼的組裝過程,只給出了幾行代碼展示一下字節碼的組裝\n // 最終返回組裝好的字節碼文件\n return var13.toByteArray();\n }\n }"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在"},{"type":"codeinline","content":[{"type":"text","text":"generateClassFile"}]},{"type":"text","text":"中,你會發現裏面全部是重組字節碼的代碼, 主要是獲取"},{"type":"codeinline","content":[{"type":"text","text":"被代理類"}]},{"type":"text","text":"字節碼和"},{"type":"codeinline","content":[{"type":"text","text":"操作類InvocationHandler"}]},{"type":"text","text":"字節碼組裝出"},{"type":"codeinline","content":[{"type":"text","text":"代理類"}]},{"type":"text","text":"的字節碼,在重組的過程因爲是在"},{"type":"codeinline","content":[{"type":"text","text":"運行時"}]},{"type":"text","text":"進行了代理類的創建,無法像往常一樣new一個被代理類的實例獲取他的方法,讓代理類進行調用。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"獲取字節碼後,接下來就要將代理類的字節碼加載進JVM中了,這裏調用的是一個"},{"type":"codeinline","content":[{"type":"text","text":"return defineClass0(loader, proxyName, proxyClassFile, 0, proxyClassFile.length)"}]},{"type":"text","text":" 其中的"},{"type":"codeinline","content":[{"type":"text","text":"defineClass0"}]},{"type":"text","text":"是一個本地native 方法,傳入了"},{"type":"codeinline","content":[{"type":"text","text":"代理類名稱、類加載器、代理類的字節碼文件、文件長度參數"}]},{"type":"text","text":",從而將字節碼加載進JVM中! 代碼如下:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"private static native Class> defineClass0(ClassLoader loader, String name,\n byte[] b, int off, int len);"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"將代理類的字節碼加載進JVM後,會在方法區內生成一個"},{"type":"codeinline","content":[{"type":"text","text":"Class對象"}]},{"type":"text","text":",標識這個代理類;"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"代理類的實例生成邏輯"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面,我們知道了通過字節碼技術生成了代理類字節碼,並通過類加載器將字節碼文件加載到了JVM的方法區中生成了一個Class對象,我們如何在運行時獲取這個Class對象的實例呢? 只有獲取了對象實例纔可以使用不是~"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"還是回到"},{"type":"codeinline","content":[{"type":"text","text":"newProxyInstance"}]},{"type":"text","text":"方法中,上面我們分析了"},{"type":"codeinline","content":[{"type":"text","text":"Class> cl = getProxyClass0(loader, intfs)"}]},{"type":"text","text":"這部分邏輯,生成了Class對象"},{"type":"codeinline","content":[{"type":"text","text":"cl"}]},{"type":"text","text":",下面生辰該實例代碼,過程很簡單,相關邏輯我就直接在代碼中註釋了"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":" // 定義構造函數的參數類型,下面的一個語句使用\n private static final Class>[] constructorParams = { InvocationHandler.class };\n\n // 通過反射獲取上述獲取的Class對象的帶參構造函數,參數必須是上述定義的 InvocationHandler.class類型\n final Constructor> cons = cl.getConstructor(constructorParams);\n // 檢查權限,如果是私有權限,設爲可被訪問\n if (!Modifier.isPublic(cl.getModifiers())) {\n AccessController.doPrivileged(new PrivilegedAction() {\n public Void run() {\n cons.setAccessible(true);\n return null;\n }\n });\n }\n // 通過構造函數傳入對應 處理類h 參數,生成實例!\n return cons.newInstance(new Object[]{h});"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上述就是生成實例的代碼,生成實例後"},{"type":"codeinline","content":[{"type":"text","text":"newProxyInstance"}]},{"type":"text","text":"就返回該實例了,就可以使用了~"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":4},"content":[{"type":"text","text":"反射:在運行時獲取被代理類的字節碼"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"那如何才能在運行時獲取到被代理類的構造函數、方法、屬性等字節碼呢?"},{"type":"text","text":" 此時“"},{"type":"codeinline","content":[{"type":"text","text":"反射!"}]},{"type":"text","text":"”登場了!我們通過反射可以在運行時獲取到類的所有信息,所有哦。 "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"定義:"},{"type":"text","text":" JAVA反射機制是在運行狀態中,對於任意一個類,都能夠知道這個類的所有屬性和方法;對於任意一個對象,都能夠調用它的任意方法和屬性;這種動態獲取信息以及動態調用對象方法的功能稱爲"},{"type":"codeinline","content":[{"type":"text","text":"java語言的反射機制"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"比如,在上述所說的組裝代理類字節碼時,在獲取被代理類的所有方法時,就調用了"},{"type":"codeinline","content":[{"type":"text","text":"Method[] var5 = var4.getMethods();"}]},{"type":"text","text":" 反射中的"},{"type":"codeinline","content":[{"type":"text","text":"getMethods"}]},{"type":"text","text":"方法,通過反射獲取到了被代理類的所有方法,這樣我們就可以在運行時獲取到任何類的所有的字節碼信息了! 從而可以組裝出我們想要的代理類字節碼!"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"所以說,"},{"type":"codeinline","content":[{"type":"text","text":"反射"}]},{"type":"text","text":"也爲"},{"type":"codeinline","content":[{"type":"text","text":"動態代理"}]},{"type":"text","text":"的實現提供了"},{"type":"codeinline","content":[{"type":"text","text":"理論支持"}]},{"type":"text","text":"!!因爲只有在運行時能獲取到對應類的信息,纔可以通過信息創造出對應的我們所需要的代理類;"}]},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"源碼分析總結"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"總而言之,"},{"type":"codeinline","content":[{"type":"text","text":"動態代理"}]},{"type":"text","text":"的理論支持是可以通過"},{"type":"codeinline","content":[{"type":"text","text":"反射機制"}]},{"type":"text","text":"在"},{"type":"codeinline","content":[{"type":"text","text":"運行時"}]},{"type":"text","text":"獲取到類的所有信息,如果運行時獲取不到被代理類的信息,那還咋生成代理類。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"動態代理的大致流程:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"image","attrs":{"src":"https://static001.geekbang.org/infoq/93/9323590444a72281e3eac494cf05b63b.png","alt":null,"title":null,"style":null,"href":null,"fromPaste":true,"pastePass":true}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"通過上述流程。我們就獲得了一個代理類對象了,調用代理類對應的方法,就會執行我們規定的執行邏輯,實現對被代理類的運行時動態增強和擴展!"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"此時,我們再拿出剛開始我們用JDK proxy實現的動態代理代碼中的生成代理類的代碼:"},{"type":"codeinline","content":[{"type":"text","text":"ImplA proxyA = (ImplA)Proxy.newProxyInstance(A.getClass().getClassLoader(), A.getClass().getInterfaces(), myHandler)"}]},{"type":"text","text":" 每個參數的作用,是不是就很清晰了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"問題解答"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上面"},{"type":"codeinline","content":[{"type":"text","text":"動態代理實現流程"}]},{"type":"text","text":",我們可以回答上述的第一個"},{"type":"codeinline","content":[{"type":"text","text":"代理類爲什麼可以在運行的時候自動生成呢?如何生成的呢?"}]},{"type":"text","text":" 問題了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"對於第二個"},{"type":"codeinline","content":[{"type":"text","text":"爲什麼調用代理類的相應的代理方法就可以調用到InvocationHandler實現類的invoke方法呢?"}]},{"type":"text","text":"和第三個"},{"type":"codeinline","content":[{"type":"text","text":"爲什麼jdk proxy只支持代理有接口實現的類呢?"}]},{"type":"text","text":"問題,我們需要反編譯一下我們通過字節碼技術產生的"},{"type":"codeinline","content":[{"type":"text","text":"代理類"}]},{"type":"text","text":",如下:"}]},{"type":"codeblock","attrs":{"lang":"java"},"content":[{"type":"text","text":"final class $Proxy0 extends Proxy implements ImplA {\n private static Method m1;\n private static Method m3;\n private static Method m2;\n private static Method m0;\n \n static {\n try {\n m1 = Class.forName(\"java.lang.Object\").getMethod(\"equals\", Class.forName(\"java.lang.Object\"));\n m3 = Class.forName(\"com.test.ImplA\").getMethod(\"methoda\");\n m2 = Class.forName(\"java.lang.Object\").getMethod(\"toString\");\n m0 = Class.forName(\"java.lang.Object\").getMethod(\"hashCode\");\n } catch (NoSuchMethodException var2) {\n // ..\n }\n }\n \n public $Proxy0(InvocationHandler var1) throws {\n super(var1);\n }\n // 需要被加強的方法methoda\n public final void methoda() throws {\n try {\n super.h.invoke(this, m3, (Object[])null);\n } catch (RuntimeException | Error var2) {\n throw var2;\n } catch (Throwable var3) {\n throw new UndeclaredThrowableException(var3);\n }\n }\n\n public final boolean equals(Object var1) throws {\n // 省略部分代碼。。。\n return (Boolean)super.h.invoke(this, m1, new Object[]{var1});\n }\n public final String toString() throws {\n // 省略部分代碼。。。\n return (String)super.h.invoke(this, m2, (Object[])null);\n }\n public final int hashCode() throws {\n // 省略部分代碼。。。\n return (Integer)super.h.invoke(this, m0, (Object[])null);\n }\n}"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"上述代碼包含幾個關鍵點: "}]},{"type":"numberedlist","attrs":{"start":"1","normalizeStart":1},"content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":1,"align":null,"origin":null},"content":[{"type":"text","text":"方法爲"},{"type":"codeinline","content":[{"type":"text","text":"final"}]},{"type":"text","text":"類型,不可再被繼承"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":2,"align":null,"origin":null},"content":[{"type":"text","text":"代理名稱爲 "},{"type":"codeinline","content":[{"type":"text","text":"$Proxy"}]},{"type":"text","text":" 代理類前綴 + 遞增數字"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":3,"align":null,"origin":null},"content":[{"type":"text","text":"繼承動態代理的核心類"},{"type":"codeinline","content":[{"type":"text","text":"Proxy"}]},{"type":"text","text":", 實現了我們指定的接口"},{"type":"codeinline","content":[{"type":"text","text":"ImplA"}]}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":4,"align":null,"origin":null},"content":[{"type":"text","text":"一個帶參構造方法"},{"type":"codeinline","content":[{"type":"text","text":"$Proxy0(InvocationHandler var1)"}]},{"type":"text","text":" 傳入InvocationHandler內部調用了父類的"},{"type":"codeinline","content":[{"type":"text","text":"Proxy"}]},{"type":"text","text":"的構造函數"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":5,"align":null,"origin":null},"content":[{"type":"text","text":"methoda、toString、hashCode、equals全部調用的傳入的InvocationHandler參數的 "},{"type":"codeinline","content":[{"type":"text","text":"invoke"}]},{"type":"text","text":"方法!!! "}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"現在回答第二個問題"},{"type":"codeinline","content":[{"type":"text","text":"爲什麼調用代理類的相應的代理方法就可以調用到InvocationHandler實現類的invoke方法呢?"}]},{"type":"text","text":" "}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"顯而易見,代理類內部的代理方法全部顯式調用的InvocationHandler實現類的invoke方法"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"第三個問題"},{"type":"codeinline","content":[{"type":"text","text":"爲什麼jdk proxy只支持代理有接口實現的類呢?"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"因爲代理類在使用JDK proxy方式生成代理類時,默認繼承Proxy類,又因爲java語言是單繼承不支持多繼承,那怎樣才能標識我要代理什麼類型的類或是代理什麼方法呢? 接口唄,java支持接口的多繼承,多少個都ok~"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好了,上述將動態代理的使用方式 和 實現原理統一過了一遍,也回答了幾個容易疑惑的問題,下面我們簡單說下動態代理在現實的java框架大家庭中的一些典型應用"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":3},"content":[{"type":"text","text":"動態代理的應用"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"**"},{"type":"codeinline","content":[{"type":"text","text":"spring aop"}]},{"type":"text","text":"** : 這可以說是spring框架中最典型的應用了,通過動態代理在運行時產生代理類,完成對被代理類的增強和功能附加"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"**"},{"type":"codeinline","content":[{"type":"text","text":"RPC框架的實現"}]},{"type":"text","text":"** : 遠程過程調用,RPC使得調用遠程方法和調用本地方法一樣,這是怎麼搞的呢?服務方對外放出服務的接口api,調用方拿到接口api,通過動態代理的方式生成一個代理類,代理類的處理類的invoke方法可以通過websocket連接遠程服務器調用對應的遠程接口; 這樣我們再用代理對象進行調用對應方法時時,就像調用本地方法一樣了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"**"},{"type":"codeinline","content":[{"type":"text","text":"mybatis框架中"}]},{"type":"text","text":"** : mapper.xml中編寫sql語句,mapper.java接口寫上對應的方法簽名;我們直接調用mapper.java中的方法就可以執行對應的sql語句,有沒有想過爲什麼? 框架使用動態代理創建一個mapper.java的代理對象,代理對象的處理類invoke中執行sql,就ok了"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"heading","attrs":{"align":null,"level":2},"content":[{"type":"text","text":"總結"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"代理分爲"},{"type":"codeinline","content":[{"type":"text","text":"靜態代理"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"動態代理"}]},{"type":"text","text":",動態代理的兩種實現方式:"},{"type":"codeinline","content":[{"type":"text","text":"JDK Proxy"}]},{"type":"text","text":"和"},{"type":"codeinline","content":[{"type":"text","text":"CGLib"}]},{"type":"text","text":",動態代理的"},{"type":"codeinline","content":[{"type":"text","text":"核心反射機制"}]},{"type":"text","text":",通過反射在運行時獲取被代理類字節碼和處理類字節碼,動態代理代理類的生成通過"},{"type":"codeinline","content":[{"type":"text","text":"重組字節碼"}]},{"type":"text","text":"的方式。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"strong"}],"text":"原創不易,有收穫的話,"},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong"}],"text":"關注"}],"marks":[{"type":"strong"}]},{"type":"text","marks":[{"type":"strong"}],"text":"、"},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong"}],"text":"點贊"}],"marks":[{"type":"strong"}]},{"type":"text","marks":[{"type":"strong"}],"text":"、"},{"type":"codeinline","content":[{"type":"text","marks":[{"type":"strong"}],"text":"評論"}],"marks":[{"type":"strong"}]},{"type":"text","marks":[{"type":"strong"}],"text":"三連支持,我最大的動力~"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"blockquote","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"關於博文有任何問題請不吝評論,感謝"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"參考:JDK源碼,https://www.jianshu.com/p/861223789d53"}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章