[TOC]
- 程序在運(yùn)行時把對應(yīng)的類加載到內(nèi)存中,在Android上來說就是把Dex文件中的類加載到內(nèi)存。
- 雙親委派機(jī)制
public abstract class ClassLoader {
private ClassLoader(Void unused, ClassLoader parent) {
this.parent = parent;
}
protected ClassLoader(ClassLoader parent) {
this(checkCreateClassLoader(), parent);
}
protected ClassLoader() {
this(checkCreateClassLoader(), getSystemClassLoader());
}
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", ".");
String librarySearchPath = System.getProperty("java.library.path", "");
return new PathClassLoader(classPath, librarySearchPath, BootClassLoader.getInstance());
}
public Class<?> loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
protected Class<?> loadClass(String name, boolean resolve)
throws ClassNotFoundException
{
// First, check if the class has already been loaded
Class<?> c = findLoadedClass(name);
if (c == null) {
try {
if (parent != null) {
c = parent.loadClass(name, false);
} else {
c = findBootstrapClassOrNull(name);
}
} catch (ClassNotFoundException e) {
// ClassNotFoundException thrown if class not found
// from the non-null parent class loader
}
if (c == null) {
// If still not found, then invoke findClass in order
// to find the class.
c = findClass(name);
}
}
return c;
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new ClassNotFoundException(name);
}
}
1. ClassLoader 繼承關(guān)系
繼承關(guān)系
[圖片上傳失敗...(image-d446ce-1549854936566)]
-
PathClassLoader
只能加載已經(jīng)安裝到Android系統(tǒng)中的apk文件(/data/app目錄)跑芳,是Android默認(rèn)使用的類加載器。 -
DexClassLoader
可以加載任意目錄下的dex/jar/apk/zip文件贬媒,比PathClassLoader更靈活聋亡,是實(shí)現(xiàn)熱修復(fù)的重點(diǎn)。
源碼查看(基于API28 9.0)
在8.0以上际乘,optimizedDirectory參數(shù)傳的都是null坡倔,也就是說PathClassLoader
和DexClassLoader
沒差別,DexClassLoader
可以加載未安裝的apk脖含,PathClassLoader也可以罪塔。
/**
* Provides a simple {@link ClassLoader} implementation that operates on a list
* of files and directories in the local file system, but does not attempt to
* load classes from the network. Android uses this class for its system class
* loader and for its application class loader(s).
*///
public class PathClassLoader extends BaseDexClassLoader {
public PathClassLoader(String dexPath, ClassLoader parent) {
super(dexPath, null, null, parent);
}
public PathClassLoader(String dexPath, String librarySearchPath, ClassLoader parent){
super(dexPath, null, librarySearchPath, parent);
}
}
/**
* A class loader that loads classes from {@code .jar} and {@code .apk} files
* containing a {@code classes.dex} entry. This can be used to execute code not
* installed as part of an application.
*///
public class DexClassLoader extends BaseDexClassLoader {
public DexClassLoader(String dexPath, String optimizedDirectory,
String librarySearchPath, ClassLoader parent) {
super(dexPath, null, librarySearchPath, parent);
}
}
具體實(shí)現(xiàn)還得看BaseDexClassLoader
的構(gòu)造方法。
public class BaseDexClassLoader extends ClassLoader {
private final DexPathList pathList;
public BaseDexClassLoader(String dexPath, File optimizedDirectory,
String librarySearchPath, ClassLoader parent) {
this(dexPath, optimizedDirectory, librarySearchPath, parent, false);
}
// 參數(shù)dexPath:待加載的apk/dex/jar文件路徑养葵;
// 參數(shù)optimizedDirectory:dex的輸出路徑征堪,將apk/dex/jar解壓出dex文件,復(fù)制到指定路徑关拒,用于dalvik運(yùn)行
// 參數(shù)librarySearchPath:加載時候需要用到的lib庫佃蚜,這個一般不用,可以傳入Null
// 參數(shù)parent:指定父加載器
public BaseDexClassLoader(String dexPath, File optimizedDirectory,
String librarySearchPath, ClassLoader parent, boolean isTrusted) {
super(parent);
this.pathList = new DexPathList(this, dexPath, librarySearchPath, null, isTrusted);
...
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
...
Class c = pathList.findClass(name, suppressedExceptions);
...
return c;
}
@Override
protected URL findResource(String name) {
return pathList.findResource(name);
}
@Override
public String findLibrary(String name) {
return pathList.findLibrary(name);
}
}
構(gòu)造方法中創(chuàng)建了一個DexPathList對象
着绊,而BaseDexClassLoader
中的各個findxxx()
調(diào)用的是DexPathList對象.findxxx()
DexPathList的構(gòu)造方法和findxxx()方法谐算。
final class DexPathList {
private Element[] dexElements;
DexPathList(ClassLoader definingContext, String dexPath,
String librarySearchPath, File optimizedDirectory, boolean isTrusted) {
...
// 加載dexPath路徑下的dex和resource
this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory, suppressedExceptions, definingContext, isTrusted);
...
}
private static Element[] makeDexElements(List<File> files, File optimizedDirectory,
List<IOException> suppressedExceptions, ClassLoader loader, boolean isTrusted) {
Element[] elements = new Element[files.size()];
int elementsPos = 0;
for (File file : files) {
if (file.isDirectory()) {
elements[elementsPos++] = new Element(file);
} else if (file.isFile()) {
String name = file.getName();
DexFile dex = null;
if (name.endsWith(DEX_SUFFIX)) {
// Raw dex file (not inside a zip/jar).
try {
dex = loadDexFile(file, optimizedDirectory, loader, elements);
if (dex != null) {
elements[elementsPos++] = new Element(dex, null);
}
} catch (IOException suppressed) {
System.logE("Unable to load dex file: " + file, suppressed);
suppressedExceptions.add(suppressed);
}
} else {
try {
dex = loadDexFile(file, optimizedDirectory, loader, elements);
} catch (IOException suppressed) {
suppressedExceptions.add(suppressed);
}
if (dex == null) {
elements[elementsPos++] = new Element(file);
} else {
elements[elementsPos++] = new Element(dex, file);
}
}
} else {
System.logW("ClassLoader referenced unknown path: " + file);
}
}
return elements;
}
}
挨個文件中尋找Class對象
public Class<?> findClass(String name, List<Throwable> suppressed) {
for (Element element : dexElements) {
Class<?> clazz = element.findClass(name, definingContext, suppressed);
if (clazz != null) {
return clazz;
}
}
if (dexElementsSuppressedExceptions != null) {
suppressed.addAll(Arrays.asList(dexElementsSuppressedExceptions));
}
return null;
}
2. 熱更新實(shí)現(xiàn)原理
如果是.dex
后綴的文件,會直接放到dexElements
數(shù)組中归露,否則就從這個文件中尋找dex
文件洲脂,找到后放到dexElements
數(shù)組。
ClassLoader#loadClass
就是遍歷dexElements
數(shù)組剧包,從dex
文件中找到要找的class
文件恐锦。
那我們是不是在這個數(shù)組前安插一個自己的數(shù)組往果,是不是就可以了?
做法:
拿到我當(dāng)前應(yīng)用的dexElements
數(shù)組,然后拿到已修復(fù)的dex或apk
文件的dexElements
數(shù)組一铅,把已修復(fù)的數(shù)組放到當(dāng)前應(yīng)用的數(shù)組前面陕贮。
public class HotfixApplication extends Application {
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
File apk = new File(getCacheDir() + "/hotfix.dex");
if (apk.exists()) {
try {
//1. 獲取當(dāng)前應(yīng)用的dexElements數(shù)組
ClassLoader classLoader = getClassLoader();
Class loaderClass = BaseDexClassLoader.class;
Field pathListField = loaderClass.getDeclaredField("pathList");
pathListField.setAccessible(true);
Object pathListObject = pathListField.get(classLoader);
Class pathListClass = pathListObject.getClass();
Field dexElementsField = pathListClass.getDeclaredField("dexElements");
dexElementsField.setAccessible(true);
Object dexElementsObject = dexElementsField.get(pathListObject);
//2. 獲取已修復(fù)dex或apk的dexElements數(shù)組
PathClassLoader newClassLoader = new PathClassLoader(apk.getPath(), null);
Object newPathListObject = pathListField.get(newClassLoader);
Object newDexElementsObject = dexElementsField.get(newPathListObject);
//3. 數(shù)組合并,把修復(fù)的數(shù)組放在自己的數(shù)組前面
int oldLength = Array.getLength(dexElementsObject);
int newLength = Array.getLength(newDexElementsObject);
Object concatDexElementsObject = Array.newInstance(dexElementsObject.getClass().getComponentType(), oldLength + newLength);
for (int i = 0; i < newLength; i++) {
Array.set(concatDexElementsObject, i, Array.get(newDexElementsObject, i));
}
for (int i = 0; i < oldLength; i++) {
Array.set(concatDexElementsObject, newLength + i, Array.get(dexElementsObject, i));
}
dexElementsField.set(pathListObject, concatDexElementsObject);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
3. 插件化原理
利用ClassLoader
在新的apk中loadClass
馅闽,利用反射獲取新的apk中的class
3.1 問題
Q: 怎么啟動插件apk中的Activity飘蚯?
A: 由于啟動Activity系統(tǒng)會校驗(yàn)清單文件,如果沒有該Activity會異常福也。我們可以創(chuàng)建一個代理的Activity,啟動這個代理Activity攀圈,然后在代理Activity中執(zhí)行真實(shí)對象的方法(這個真實(shí)對象需要有和Activity一樣的方法)暴凑。
Q: 怎樣獲取插件apk中的Resource文件
A: 我們要知道,Resource也是利用AssetManager
獲取的赘来,所以我們要自定義一個AssetManager
现喳,安放到Resource對象中。
public class ProxyActivity extends Activity {
Object realActivity;
// realActivity = ???;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// realActivity.onCreate(savedInstanceState);
}
@Override
public AssetManager getAssets() {
try {
Class assetManagerClass = AssetManager.class;
AssetManager assetManager = (AssetManager) assetManagerClass.newInstance();
Method addAssetPath = assetManagerClass.getDeclaredMethod("adAssetPath", String.class);
addAssetPath.invoke(assetManager, "apkPath");
return assetManager;
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return super.getAssets();
}
@Override
public Resources getResources() {
return new Resources(getAssets(), getResources().getDisplayMetrics(), getResources().getConfiguration());
}
}