類載入機制中的雙親委派模型是非常重要的,本文從源碼的角度對雙親委派模式進行瞭解析,源碼調用基本邏輯很簡單. ...
Launcher啟動類
本文是雙親委派機制的源碼分析部分,類載入機制中的雙親委派模型對於jvm的穩定運行是非常重要的 不過源碼其實比較簡單,接下來簡單介紹一下 我們先從啟動類說起 有一個Launcher類 sun.misc.Launcher;

sun.misc.Launcher 這個類是系統用於啟動主應用的啟動器 |
創建 擴展 類載入器 |
創建 應用程式 類載入器 |
設置ContextClassLoader |
如果需要安裝安全管理器 security manager |






ClassLoader的構造方法
前面說過,對於虛擬機來說只有兩種類載入器 啟動類載入器以及其他所有,而其他所有都是java.lang.ClassLoader的子類 所以想要自定義類載入器,必須要繼承實現ClassLoader 而且,我們上面說到的,java給我們提供的AppClassLoader 和 ExtClassLoader 也都是ClassLoader的子類 看下ClassLoader的構造方法 和變數parent 你會發現,其實構造方法實際上只有雙參數版本這一種 第二個參數為parent,這個parent是一個ClassLoader, 用於記錄他的 父 類載入器不管調用哪個構造方法 parent必然會被初始化 要麼是你調用帶參數的構造方法, 顯式指定一個來設置parent 如果你不指定,預設的構造方法,會使用 getSystemClassLoader返回的AppClassLoader 設置parent |

getSystemClassLoader 獲取AppClassLoader 的過程 |



loadClass與findClass
想要實現類 載入器,需要繼承ClassLoader 並且有兩個重要的方法 看下兩個重要方法的聲明,你可能就感覺出來了,想想public 和 protected都是啥意思?
loadClass方法是類載入器執行 載入類邏輯 的方法,包括檢查是否已經載入,調用父類載入,失敗則自己嘗試使用 findClass方法載入 |
findClass當前類載入器 實際執行載入二進位流的具體行為方法 |
Launcher.APPClassLoader中的loadClass方法,最終調用的是super.loadClass , 實際上就是ClassLoader的loadClass方法 Launcher.ExtClassLoader 根本就沒有實現自己的loadClass 方法,所以使用的也是ClassLoader中的 |




