一、Android虛擬機(jī)加載class原理
我們知道Java在運(yùn)行時加載對應(yīng)的類是通過ClassLoader來實(shí)現(xiàn)的蛔垢,ClassLoader本身是一個抽象來,Android中使用PathClassLoader類作為Android的默認(rèn)的類加載器,
PathClassLoader其實(shí)實(shí)現(xiàn)的就是簡單的從文件系統(tǒng)中加載類文件。PathClassLoade本身繼承自BaseDexClasoader衙耕,BaseDexClassLoader重寫了findClass方法。
詳細(xì)的可以看這篇文章:Android熱更新實(shí)現(xiàn)原理勺远,本篇文章不做介紹橙喘,這里只從源碼上講解multidex的實(shí)現(xiàn)原理。
二胶逢、源碼解析
- 首先從Multidex.install方法開始分析厅瞎,以下是install的核心代碼:
public static void install(Context context) {
Log.i(TAG, "install");
if (IS_VM_MULTIDEX_CAPABLE) {
Log.i(TAG, "VM has multidex support, MultiDex support library is disabled.");
return;
}
if (Build.VERSION.SDK_INT < MIN_SDK_VERSION) {
throw new RuntimeException("Multi dex installation failed. SDK " + Build.VERSION.SDK_INT
+ " is unsupported. Min SDK version is " + MIN_SDK_VERSION + ".");
}
try {
ApplicationInfo applicationInfo = getApplicationInfo(context);
if (applicationInfo == null) {
// Looks like running on a test Context, so just return without patching.
return;
}
synchronized (installedApk) {
String apkPath = applicationInfo.sourceDir;
if (installedApk.contains(apkPath)) {
return;
}
installedApk.add(apkPath);
if (Build.VERSION.SDK_INT > MAX_SUPPORTED_SDK_VERSION) {
......
}
ClassLoader loader;
try {
//這里獲取到BaseDexClassLoader的類加載器。
loader = context.getClassLoader();
} catch (RuntimeException e) {
return;
}
if (loader == null) {
return;
}
try {
clearOldDexDir(context);
} catch (Throwable t) {
}
File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);
List<File> files = MultiDexExtractor.load(context, applicationInfo, dexDir, false);
if (checkValidZipFiles(files)) {
//這里加載第二個dex文件
installSecondaryDexes(loader, dexDir, files);
} else {
// Try again, but this time force a reload of the zip file.
files = MultiDexExtractor.load(context, applicationInfo, dexDir, true);
if (checkValidZipFiles(files)) {
installSecondaryDexes(loader, dexDir, files);
} else {
// Second time didn't work, give up
throw new RuntimeException("Zip files were not valid.");
}
}
}
} catch (Exception e) {
Log.e(TAG, "Multidex installation failure", e);
throw new RuntimeException("Multi dex installation failed (" + e.getMessage() + ").");
}
Log.i(TAG, "install done");
}
我們先分析下面這段代碼:
private static final boolean IS_VM_MULTIDEX_CAPABLE = isVMMultidexCapable(System.getProperty("java.vm.version"));
private static final int MIN_SDK_VERSION = 4; //4是android 1.6
public static void install(Context context) {
Log.i(TAG, "install");
//isVMMultidexCapable()方法,判斷虛擬機(jī)是否支持multidex
if (IS_VM_MULTIDEX_CAPABLE) {
Log.i(TAG, "VM has multidex support, MultiDex support library is disabled.");
return;
}
//在sdk1.6以前是不支持multidex的
if (Build.VERSION.SDK_INT < MIN_SDK_VERSION) {
throw new RuntimeException("Multi dex installation failed. SDK " + Build.VERSION.SDK_INT
+ " is unsupported. Min SDK version is " + MIN_SDK_VERSION + ".");
}
.......
}
我們看下isVMMultidexCapable方法:
//這里的versionString是 java.vm.version
static boolean isVMMultidexCapable(String versionString) {
boolean isMultidexCapable = false;
if (versionString != null) {
Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(versionString);
if (matcher.matches()) {
try {
int major = Integer.parseInt(matcher.group(1));
int minor = Integer.parseInt(matcher.group(2));
isMultidexCapable = (major > VM_WITH_MULTIDEX_VERSION_MAJOR)
|| ((major == VM_WITH_MULTIDEX_VERSION_MAJOR)
&& (minor >= VM_WITH_MULTIDEX_VERSION_MINOR));
} catch (NumberFormatException e) {
// let isMultidexCapable be false
}
}
}
Log.i(TAG, "VM with version " + versionString +
(isMultidexCapable ?
" has multidex support" :
" does not have multidex support"));
return isMultidexCapable;
}
getProperty()的參數(shù):
mean | name | example |
---|---|---|
java.vm.version | VM implementation version | 1.2.0 |
這里主要判斷虛擬機(jī)是否已經(jīng)支持multidex初坠,如不支持就直接返回和簸。
繼續(xù)分析,經(jīng)過一系列的判斷碟刺,驗(yàn)證等步驟锁保,最終會執(zhí)行installSecondaryDexes方法,這個方法才是加載我們拆分的dex文件:
private static void installSecondaryDexes(ClassLoader loader, File dexDir, List<File> files)
throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException,
InvocationTargetException, NoSuchMethodException, IOException {
if (!files.isEmpty()) {
if (Build.VERSION.SDK_INT >= 19) {
V19.install(loader, files, dexDir);
} else if (Build.VERSION.SDK_INT >= 14) {
V14.install(loader, files, dexDir);
} else {
V4.install(loader, files);
}
}
}
首先判斷半沽,當(dāng)前的sdk版本爽柒,有3個不同的方法,分別是V19 V14 V4者填,我們分析下V19.install方法
private static void install(ClassLoader loader, List<File> additionalClassPathEntries,
File optimizedDirectory)
throws IllegalArgumentException, IllegalAccessException,
NoSuchFieldException, InvocationTargetException, NoSuchMethodException {
/* The patched class loader is expected to be a descendant of
* dalvik.system.BaseDexClassLoader. We modify its
* dalvik.system.DexPathList pathList field to append additional DEX
* file entries.
*/
//這里通過反射獲取BaseClassLoader中的變量名為”pathList“ Field
Field pathListField = findField(loader, "pathList");
//這里拿到pathList這個對象
Object dexPathList = pathListField.get(loader);
ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();
//關(guān)鍵步驟浩村,反射調(diào)用makeDexElements函數(shù),
expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList,
new ArrayList<File>(additionalClassPathEntries), optimizedDirectory,
suppressedExceptions));
if (suppressedExceptions.size() > 0) {
for (IOException e : suppressedExceptions) {
Log.w(TAG, "Exception in makeDexElement", e);
}
Field suppressedExceptionsField =
findField(loader, "dexElementsSuppressedExceptions");
IOException[] dexElementsSuppressedExceptions =
(IOException[]) suppressedExceptionsField.get(loader);
if (dexElementsSuppressedExceptions == null) {
dexElementsSuppressedExceptions =
suppressedExceptions.toArray(
new IOException[suppressedExceptions.size()]);
} else {
IOException[] combined =
new IOException[suppressedExceptions.size() +
dexElementsSuppressedExceptions.length];
suppressedExceptions.toArray(combined);
System.arraycopy(dexElementsSuppressedExceptions, 0, combined,
suppressedExceptions.size(), dexElementsSuppressedExceptions.length);
dexElementsSuppressedExceptions = combined;
}
suppressedExceptionsField.set(loader, dexElementsSuppressedExceptions);
}
}
這里的pathDexList是BaseClassLoader下面的一個成員變量幔托,它的類型是DexPathList穴亏,這個類主要負(fù)責(zé)加載Dex并重組;接著看下expandFieldArray的源碼重挑,這個函數(shù)主要的目的是嗓化,先通過反射拿到名為dexElements的field,這個dexElements就是我們剛剛說的Elements數(shù)組谬哀,然后將剛剛makeDexElements生成的Elements數(shù)組放在dexElements的首部刺覆,makeDexElements生成的數(shù)組就是加載Dex文件的數(shù)組,這樣就完成了將dex的class放在ClassLoader前面的功能史煎。
/**
* Replace the value of a field containing a non null array, by a new array containing the
* elements of the original array plus the elements of extraElements.
* @param instance the instance whose field is to be modified.
* @param fieldName the field to modify.
* @param extraElements elements to append at the end of the array.
*/
private static void expandFieldArray(Object instance, String fieldName,
Object[] extraElements) throws NoSuchFieldException, IllegalArgumentException,
IllegalAccessException {
Field jlrField = findField(instance, fieldName);
Object[] original = (Object[]) jlrField.get(instance);
Object[] combined = (Object[]) Array.newInstance(
original.getClass().getComponentType(), original.length + extraElements.length);
System.arraycopy(original, 0, combined, 0, original.length);
System.arraycopy(extraElements, 0, combined, original.length, extraElements.length);
jlrField.set(instance, combined);
}
最后分析下makeDexElements這個函數(shù)谦屑,首先調(diào)用的是V19下面的makeDexElements函數(shù):
/**
* A wrapper around
* {@code private static final dalvik.system.DexPathList#makeDexElements}.
*/
private static Object[] makeDexElements(
Object dexPathList, ArrayList<File> files, File optimizedDirectory,
ArrayList<IOException> suppressedExceptions)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
Method makeDexElements =
findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class,
ArrayList.class);
return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory,
suppressedExceptions);
}
事實(shí)上,也是通過反射調(diào)用DexPathList里面的makeDexElements方法篇梭,具體就不做分析氢橙。
private static Element[] makeDexElements(ArrayList<File> files, File optimizedDirectory, ArrayList<IOException> suppressedExceptions) {
ArrayList<Element> elements = new ArrayList<Element>();
for (File file : files) {
File zip = null;
DexFile dex = null;
String name = file.getName();
if (file.isDirectory()) {
elements.add(new Element(file, true, null, null));
} else if (file.isFile()){
if (name.endsWith(DEX_SUFFIX)) {
try {
dex = loadDexFile(file, optimizedDirectory);
} catch (IOException ex) {
System.logE("Unable to load dex file: " + file, ex);
}
} else {
zip = file;
try {
dex = loadDexFile(file, optimizedDirectory);
} catch (IOException suppressed) {
suppressedExceptions.add(suppressed);
}
}
} else {
System.logW("ClassLoader referenced unknown path: " + file);
}
if ((zip != null) || (dex != null)) {
elements.add(new Element(file, false, zip, dex));
}
}
return elements.toArray(new Element[elements.size()]);
}