Android 插件化,熱修復(fù)淺析

1、ClassLoader:首先熟悉下ClassLoader,當(dāng)java的類被編譯成Class文件時(shí),如果想翻譯成機(jī)器碼則必須通過JVM虛擬機(jī)中的ClassLoader來進(jìn)行加載。
Android中ClassLoader分為三種(當(dāng)然還有其他但是這里只介紹三種):
BootClassLoader:加載Android Framework層class文件。

PathClassLoader:加載已經(jīng)安裝在手機(jī)上的APK的class文件。

DexClassLoader:用于加載指定目錄中的class文件。(插件,熱修復(fù)等都是通過這個(gè)來完成)

2、雙親代理模式:

先解釋什么叫雙親代理,當(dāng)一個(gè)class文件被加載時(shí),classloader會在自己的緩存中查找這個(gè)class文件是不是被加載過,如果已經(jīng)加載就直接返回不重新加載,如果沒有被加載則會查找父ClassLoader是不是加載過,如果所有的ClassLoader都沒加載過則一層層返回到當(dāng)前ClassLoader,進(jìn)行加載。

再來熟悉下Android中ClassLoader,如圖所示:

Android 中ClassLoader類的繼承關(guān)系

這只是classloader的類繼承關(guān)系并不是剛才所講的雙親代理的父子關(guān)系。
真正雙親代理中的查找順序是:DexClassLoader--->PathClassLoader--> BaseDexClassLoader(平常所用到的插件化,熱修復(fù)都是通過這三種ClassLoader來實(shí)現(xiàn),其他不做介紹)但是PathClassLoader并不是DexClassLoader的父類。這里需要注意下。

3、簡述插件化,熱修復(fù)等技術(shù)的原理:

其實(shí)就一句話,利用雙親代理。
先說插件化:一個(gè)插件被會被一個(gè)自定義的DexClassLoader來加載,通過雙親代理模式則肯定會找不到,則會自定義的這個(gè)DexClassLoader來加載從而達(dá)到不安裝就可以被調(diào)用的效果
再說熱修復(fù):Android程序中的Class文件會被封裝成一個(gè)或者多個(gè)Dex文件(這個(gè)將APK解壓就會看出來),在剛才提到的DexClassLoader和PathClassLoader是怎么加載Dex文件呢?

下面看他們倆的父類BaseDexClassLoader的構(gòu)造函數(shù):


/**
 * Constructs an instance.
 *
 * @param dexPath the list of jar/apk files containing classes and
 * resources, delimited by {@code File.pathSeparator}, which
 * defaults to {@code ":"} on Android
 * @param optimizedDirectory directory where optimized dex files
 * should be written; may be {@code null}
 * @param librarySearchPath the list of directories containing native
 * libraries, delimited by {@code File.pathSeparator}; may be
 * {@code null}
 * @param parent the parent class loader
 */
public BaseDexClassLoader(String dexPath, File optimizedDirectory,
        String librarySearchPath, ClassLoader parent) {
    super(parent);
    this.pathList = new DexPathList(this, dexPath, librarySearchPath, optimizedDirectory);
}

(為了簡單弄明白熱修復(fù)的原理不做展開只介紹熱修復(fù)簡單原理)
在這里有一個(gè)名為pathList的DexPathList對象,再看DexPathList的構(gòu)造函數(shù)


public DexPathList(ClassLoader definingContext, String dexPath,
        String librarySearchPath, File optimizedDirectory) {
//省略部分代碼
//賦值類加載器
    this.definingContext = definingContext;
    // 將dex文件或壓縮包中的信息保存到dexElements中
    this.dexElements = makeDexElements(splitDexPath(dexPath), optimizedDirectory, suppressedExceptions, definingContext);
   //省略部分代碼
}

這里看到了咱們剛才提到的Dex的影子,再看makeDexElements方法

/**
 * Makes an array of dex/resource path elements, one per element of
 * the given array.
 */
private static Element[] makeDexElements(List<File> files, File optimizedDirectory,List<IOException> suppressedExceptions,ClassLoader loader) {
    return makeElements(files,optimizedDirectory,suppressedExceptions,false,loader);
}
是個(gè)重載,繼續(xù)看看makeElements方法:
private static Element[] makeElements(List<File> files, File optimizedDirectory,List<IOException> suppressedExceptions,boolean ignoreDexFiles,ClassLoader loader) {
//實(shí)例化dex文件或者包含dex文件的的文件長度的Element數(shù)組
    Element[] elements = new Element[files.size()];
    int elementsPos = 0;
    /*
     * Open all files and load the (direct or contained) dex files
     * up front.
     */
    for (File file : files) {
        File zip = null;
        File dir = new File("");
        DexFile dex = null;
        String path = file.getPath();
        String name = file.getName();
 
    //省略部分代碼
//如果是dex文件
     if (name.endsWith(DEX_SUFFIX)) {
         dex = loadDexFile(file, optimizedDirectory, loader,elements); 
      } else {
//如果是那些包含dex文件的壓縮文件
       zip = file;
dex = loadDexFile(file, optimizedDirectory, loader, elements);
            }
        } 
//省略部分代碼
    return elements;
}

代碼不復(fù)雜就是將一個(gè)個(gè)的Dex來封裝成Element,在返回來看DexClassLoader和PathClassLoader從BaseDexClassLoader繼承過來的方法findCLass,


@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
   List<Throwable> suppressedExceptions = new ArrayList<Throwable>();
   Class c = pathList.findClass(name, suppressedExceptions);
   if (c == null) {
       ClassNotFoundException cnfe = new ClassNotFoundException("Didn't find class \"" + name + "\" on path: " + pathList);
       for (Throwable t : suppressedExceptions) {
           cnfe.addSuppressed(t);
       }
       throw cnfe;
   }
   return c;
}

看到了嗎?pathList出現(xiàn)了,傳入的是一個(gè)class 的name并返回了一個(gè)Class對象,現(xiàn)在開始追蹤pathList的findClass方法,

/**
* Finds the named class in one of the dex files pointed at by
* this instance. This will find the one in the earliest listed
* path element. If the class is found but has not yet been
* defined, then this method will define it in the defining
* context that this instance was constructed with.
*
* @param name of class to find
* @param suppressed exceptions encountered whilst finding the class
* @return the named class or {@code null} if the class is not
* found in any of the dex files
*/
public Class findClass(String name, List<Throwable> suppressed) {
   for (Element element : dexElements) {
       DexFile dex = element.dexFile;

       if (dex != null) {
           Class clazz = dex.loadClassBinaryName(name, definingContext, suppressed);
           if (clazz != null) {
               return clazz;
           }
       }
   }
   if (dexElementsSuppressedExceptions != null) {
       suppressed.addAll(Arrays.asList(dexElementsSuppressedExceptions));
   }
   return null;
}

看到了剛才說的Element的身影,pathList中的findClass方法會遍歷當(dāng)前ClassLoader中的Element,并將Element轉(zhuǎn)換成Dex文件,Dex文件獲取指定Class的對象,直到獲取到對應(yīng)的Class為止。

了解了加載Class的流程后就不難解釋熱修復(fù)是怎么做的了,我們只需要將修復(fù)過的Dex文件放在存在Bug的Dex的前面就可以,因?yàn)殡p親代理模式當(dāng)一個(gè)Class被加載過了就不會再去加載而是從緩存中的獲取

參考鏈接

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容