public class PathClassLoader extends BaseDexClassLoader {
37 public PathClassLoader(String dexPath, ClassLoader parent) {
38 super(dexPath, null, null, parent);
39 }
40
63 public PathClassLoader(String dexPath, String libraryPath,
64 ClassLoader parent) {
65 super(dexPath, null, libraryPath, parent);
66 }
67}
68
DexClassLoader源碼以下:
private static Element[] makeDexElements(ArrayList<File> files, File optimizedDirectory,
ArrayList<IOException> suppressedExceptions) {
ArrayList<Element> elements = new ArrayList<Element>();
209 /*
210 * Open all files and load the (direct or contained) dex files
211 * up front.
212 */
213 for (File file : files) {//遍歷所有的dex文件
214 File zip = null;
215 DexFile dex = null;//這是核心的類,處理將dex文件轉化成對應的DexFile對象
216 String name = file.getName();
217
218 if (name.endsWith(DEX_SUFFIX)) {//.dex結尾(針對PathClassLoader處理)
219 // Raw dex file (not inside a zip/jar).
220 try {
221 dex = loadDexFile(file, optimizedDirectory);//核心方法,內部是調用的DexFile的loadDex()方法
222 } catch (IOException ex) {
223 System.logE("Unable to load dex file: " + file, ex);
224 }
225 } else if (name.endsWith(APK_SUFFIX) || name.endsWith(JAR_SUFFIX)
226 || name.endsWith(ZIP_SUFFIX)) {//.dex .jar .apk 結尾 (針對DexClassLoader處理)
227 zip = file;
228
229 try {
230 dex = loadDexFile(file, optimizedDirectory);
231 } catch (IOException suppressed) {
232 /*
233 * IOException might get thrown "legitimately" by the DexFile constructor if the
234 * zip file turns out to be resource-only (that is, no classes.dex file in it).
235 * Let dex == null and hang on to the exception to add to the tea-leaves for
236 * when findClass returns null.
237 */
238 suppressedExceptions.add(suppressed);
239 }
240 } else if (file.isDirectory()) {
241 // We support directories for looking up resources.
242 // This is only useful for running libcore tests.
243 elements.add(new Element(file, true, null, null));//創建Element對象
244 } else {
245 System.logW("Unknown file type for: " + file);
246 }
247
248 if ((zip != null) || (dex != null)) {
249 elements.add(new Element(file, false, zip, dex));
250 }
251 }
252
253 return elements.toArray(new Element[elements.size()]);
254 }
3.Context的getClassLoader()為何返回是PathClassLoader,探索其中奧秘
我們都知道getApplicationContext()的返回的實現類是ContextImpl,下面來看看ContextImpl的getClassLoader()的代碼實現:
public ClassLoader getClassLoader() {
return mPackageInfo != null ?
mPackageInfo.getClassLoader() : ClassLoader.getSystemClassLoader();
}
我們看到如果mPackageInfo不為null,就調用它的getClassLoader()方法,否則調用ClassLoader.getSystemClassLoader(),這里我們看到了ClassLoader的getSystemClassLoader()方法,但是這里還不是重點,重點是mPackageInfo這個對象,這是甚么呢,它是1個LoadedAPK對象。它又是甚么呢?
官方文檔說明以下:
Local state maintained about a currently loaded .apk.
LoaderAPK對象是apk在內存中的表示。通過這個LoaderApk對象可以拿到apk中代碼和資源,乃至里面Activity和Service等信息。
那末它又是哪里創建的,又是甚么時候創建的呢,如果你了解Activity的啟動進程,你就明白了(如果想了解,推薦老羅的文章),這里就不贅述了。在ActivityThread里面有1個mPackages的map類型的成員變量,根據鍵值(packageName)存儲對應的LoadedApk對象。啟動Activity的時候要調用LoadedApk的getClassLoader(),來加載對應的Activity class文件,然后通過反射創建這個activity的實例;那末獲得這個對象,會先去mPackages中去查找有無緩存,如果沒有就創建1個新的LoadedAPK對象。
下面代碼截取自ActivityThread中啟動Activity的進程中創建LoadedApk的代碼:
public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
CompatibilityInfo compatInfo) {
return getPackageInfo(ai, compatInfo, null, false, true, false);
}
private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
boolean registerPackage) {
// 獲得userid信息
final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
synchronized (mResourcesManager) {
// 嘗試獲得緩存信息
WeakReference<LoadedApk> ref;
if (differentUser) {
// Caching not supported across users
ref = null;
} else if (includeCode) {
ref = mPackages.get(aInfo.packageName);
} else {
ref = mResourcePackages.get(aInfo.packageName);
}
LoadedApk packageInfo = ref != null ? ref.get() : null;
if (packageInfo == null || (packageInfo.mResources != null
&& !packageInfo.mResources.getAssets().isUpToDate())) {
// 緩存沒有命中,直接new
packageInfo =
new LoadedApk(this, aInfo, compatInfo, baseLoader,
securityViolation, includeCode &&
(aInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
// 省略。。更新緩存
return packageInfo;
}
}
下面看上面使用到的LoadedApk的構造函數,其實LoadedApk還有1個構造函數,在ContextImpl創建自己的實例的同時創建其LoadedApk的成員變量的時候使用了。
108 public LoadedApk(ActivityThread activityThread, ApplicationInfo aInfo,
109 CompatibilityInfo compatInfo,
110 ActivityThread mainThread, ClassLoader baseLoader,
111 boolean securityViolation, boolean includeCode) {
<span style="white-space:pre"> </span> .......(省略)
126
127 if (mAppDir == null) {
128 if (ActivityThread.mSystemContext == null) {//這個context很重要,1個ActivityThread只有這1個,是靜態全局的
129 ActivityThread.mSystemContext =
130 ContextImpl.createSystemContext(mainThread);
131 ActivityThread.mSystemContext.getResources().updateConfiguration(
132 mainThread.getConfiguration(),
133 mainThread.getDisplayMetricsLocked(compatInfo, false),
134 compatInfo);
135 //Slog.i(TAG, "Created system resources "
136 // + mSystemContext.getResources() + ": "
137 // + mSystemContext.getResources().getConfiguration());
138 }
139 mClassLoader = ActivityThread.mSystemContext.getClassLoader();//這個ClassLoader就是最后返回的那個ClassLoader
140 mResources = ActivityThread.mSystemContext.getResources();
141 }
142 }
143
看到這里,我們只要終究這個CLassLoader的來源是從Context那里后去的,也就是ActivityThread的mSystemContext里面的ClassLoader,我們來看1下這個mSystemContext的創建進程,代碼以下:
1458 static ContextImpl createSystemContext(ActivityThread mainThread) {
1459 ContextImpl context = new ContextImpl();
1460 context.init(Resources.getSystem(), mainThread);//這個init操作也沒有創建他里面LoadedApk成員變量
1461 return context;
1462 }
所以終究調用的代碼,就是最開始的ContextImpl的getClassLoader()方法,并且mPackageInfo(LoadedAPK對象)為null,所以終究調用的是ClassLoader.getSystemClassLoader(),所以終究結論就是系統ClassLoader是通過ClassLoader.getSystemClassLoader()創建。
4.揭開ClassLoader.getSystemClassLoader()在Android中的神秘面紗
其代碼以下:
public static ClassLoader getSystemClassLoader() {
return SystemClassLoader.loader;
}
static private class SystemClassLoader {
public static ClassLoader loader = ClassLoader.createSystemClassLoader();
}
private static ClassLoader createSystemClassLoader() {
String classPath = System.getProperty("java.class.path", ".");
return new PathClassLoader(classPath, BootClassLoader.getInstance());
}
對最有1個核心方法createSystemClassLoader(),官方說明以下:
Create the system class loader. Note this is NOT the bootstrap class
loader (which is managed by the VM). We use a null value for the parent
to indicate that the bootstrap loader is our parent.
創建系統的ClassLoader。注釋:這不是bootstrap ClassLoader(被虛擬機管理的ClassLoader)。我們使用null作為我們系統ClassLoader的parent來表明bootstrap就是我們的系統ClassLoader的parent。這里也就是充分辯明了Android系統不是使用的java原生的bootstrap來加載,而是使用自己的創建的套機制。取代bootstrap的是用null(bootstrap不是1個ClassLoader對象,所以他的子級ClassLoader調用getParent()返回的是null),而取代java中第2級的ClassLoader使用Android中創建的最基層的BootClassLoader(也就是上面的PathClassLoader的parent)。
這個BootClassLoader是單例的,所以全局只有1個,我們也能夠得出,系統所有履行裝載類的操作,都會履行到這個對象。代碼以下:
public BootClassLoader() {
super(null, true);//他的parent為null(摹擬它的parent是bootstrap)
}
還有我們看到上面PathClassLoader構造函數中傳遞的第1個參數classPath,這個就是我們之前打印出來的dexPath。為何系統的ClassLoader.getSystemClassLoader()返回的PathClassLoader 的dexPath指向的是當前apk的安裝路徑;但是我們自己創建的返回的PathClassLoader的dexPath卻是. 我們發現是由上面的System.getProperty("java.class.path",".");決定的,看到get操作,相對的也就會有set操作,那末這個值是甚么時候設置的呢。這我們就要追溯到Android
framwork中System中的initSystemProperty()方法中,調用VMRuntime.getRuntime().classPath()的值,這個值應當就是當前apk的安裝路徑。
代碼以下: 路徑:/libcore/luni/src/main/java/java/lang/System.java(4.0.4)
private static void initSystemProperties() {
VMRuntime runtime = VMRuntime.getRuntime();
Properties p = new Properties();
String projectUrl = "http://www.android.com/";
String projectName = "The Android Project";
p.put("java.boot.class.path", runtime.bootClassPath());
p.put("java.class.path", runtime.classPath());
}
但是,為何我們自己調用,獲得這個值就是. 我的料想就是 系統創建完對應的ClassLoader以后,就將這個值修改成了.(固然這僅僅是我個人的料想,希望了解的大神能幫我解答1下,由于我實在是找不到緣由,困惑好久了)。
5.總結
1.Android系統最頂級的ClassLoader是BootClassLoader(替換java中第2級的ext ClassLoader),而用來加載系統的類是使用的以這兒BootClassLoader為parent的PathClassLoader(替換java中第3級加載classpath的ClassLoader)。
2.Android系統的PathClassLoader的dexPath(要加載類的路徑),指向當前apk安裝的路徑,然后使用DexFile來解析對應的dex文件,裝載里面的class
3.DexClassLoader,主要用于加載外部插件,也就是可以直接加載1個apk文件,現在的插件化動態加載機制,熱修復等都要使用到它的特性,固然直接使用里面的DexFile直接加載dex文件也是可以(AndFix就是這樣做的)。
4.自己遇到的坑:我之前在學習動態化的時候,看完原理以后,自己創建1個DexClassLoader ,它的parent我設置的是系統PathClassLoader(也就是context.getClassLoader()),但是load外部apk中的類的時候,報錯:當前apk的安裝路徑下(也就是這個apk文件對應生成的ODEX文件)找不到對應的類,也就是ClassNotFoundException,但是自己不明白為何我用DexClassLoader加載的外部apk,但是它卻到系統中去尋覓。現在明白了由于我傳遞的是PathClassLoader的dexPath是指向系統的apk的路徑的,自然會到那里去找。但是如果傳遞的是ClassLoader.getSystemClassLoader(),由于dexPath是.
,是Directory,就不會創建DexFile,也就不會走DexFile的loadDexFile()方法,而是直接調用它的parent也就是BootClassLoader的findClass()來裝載當前類。
文章終究寫完了,鄙人愚鈍,水平有限,文章難免有錯,歡迎指出。