爲什麼PathClassLoader的父加載器(parent)是BootClassLoader?

寫在前面

雙親委託機制中,當加載一個Class的時候,如果當前ClassLoader有父加載器的時候用父加載器加載。爲什麼PathClassLoader的父加載器(parent)是BootClassLoader?

查看PathClassLoader的源碼

在這裏插入圖片描述
從上圖可知,PathClassLoader構造函數傳入了一個ClassLoader類型的參數parent。

PathClassLoader是何時創建以及parent是什麼
從哪看呢?由於ActivityThread是我們常說的UI線程,ActivityThread類中的main()方法是整個應用的入口。所以我們來看一下ActivityThread的main()。

ActivityThread類的main方法

在這裏插入圖片描述
main方法中進行了MainLooper的初始化和主線程的創建以及主線程Handler的初始化
這裏我們關注一下attach方法
在這裏插入圖片描述
在ActivityThread的attach方法中,ActivityManagerService通過attachApplication方法,將ApplicationThread對象綁定到ActivityManagerService上,mAppThread對象所對應的類是ApplicatinThread,是ActivityThread的內部類,實現了IBinder接口,用於ActivityThread和ActivityManagerService的進程間通信

我們接着看attachApplication方法
在這裏插入圖片描述
方法中調用了attachApplicationLocked方法
在這裏插入圖片描述
attachApplicationLocked方法中調用了mAppThread的bindApplication方法
在這裏插入圖片描述
bindApplication方法中創建了AppBindData對象,對象中設置了線程信息、application信息等
然後調用了sendMessage發消息,what = BIND_APPLICATION
在這裏插入圖片描述
sendMessage中封裝了一下給主線程handler:mH 發消息
在這裏插入圖片描述
主線程handler的handleMessage方法中調用handleBindApplication方法
在這裏插入圖片描述
在這裏插入圖片描述
handleBindApplication方法中代碼比較多,先關注兩點:
1.創建了ContextImpl
2.調用了ContextImpl的getClassLoader()方法
看一下如何getClassLoader的
在這裏插入圖片描述
mClassLoader和mPackageInfo是構造函數中傳入的,mClassLoader傳入的是null,mPackageInfo傳入的是data.info所以調用mPackageInfo.getClassLoader()
在這裏插入圖片描述

總結

我們寫的應用程序的Class使用PathClassLoader加載,PathClassLoader的父加載器(parent)是BootClassLoader

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章