目前来说,Android中的插件技术以及热修复技术都跟ClassLoader息息相关,了解此技术有助于加深对Android系统的 了解。尤为是对于插件技术来说,对Class的加载基本固定都是一个套路。(热修复要更复杂一些,涉及到C++层面的方法数等知识)java
最好先阅读JVM中的ClassLoader,有了这篇基础而后再看这边理解会更加深入。此外还能够谷歌关键字搜索一下相关知识,有个基础概念再看本篇文章更佳。本文不会过多重复其余BlOG中提到的概念。android
相比其余多数东拼西凑的文章,这篇文章能从头到脚帮你梳理一下Android中ClassLoader的知识点,以及代码层面帮你实战 加深理解。api
还记得在我以前的JVM那篇文章的结尾,我自定义了一个ClassLoader,经过读取了一个本地class文件,而后传递了 一个byte数组 到defineClass这个方法里从而成功的加载了一个本地class,可是在android中,这种方法是不被容许的。 咱们来看看源码:数组
android的classLoader能够看出来是有defineClass这个方法的,可是这些方法都统一返回了异常,也就是说 android官方不容许咱们用JVM那套方法来加载class,为了更清晰,我复制一段源码出来。bash
protected final Class<?> defineClass(String name, byte[] b, int off, int len,
ProtectionDomain protectionDomain)
throws ClassFormatError
{
throw new UnsupportedOperationException("can't load this type of class file");
}
复制代码
很直观,能看出来这里是什么意思,再接着往下看app
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;
}
复制代码
这里看一下,同样很直观,能够看出来这里的loadClass和JVM中的loadClass的流程如出一辙。也是符合双亲委托机制。框架
有必定基础的人应该知道,android中的类加载器有两种,DexClassLoader和PathClassLoader。咱们下面就来看看这2个 ClassLoader是如何加载class文件的吧。ide
package dalvik.system;
import dalvik.system.BaseDexClassLoader;
import java.io.File;
public class DexClassLoader extends BaseDexClassLoader {
public DexClassLoader(String dexPath, String optimizedDirectory, String librarySearchPath, ClassLoader parent) {
super((String)null, (File)null, (String)null, (ClassLoader)null);
throw new RuntimeException("Stub!");
}
}
复制代码
public class PathClassLoader extends BaseDexClassLoader {
public PathClassLoader(String dexPath, ClassLoader parent) {
super((String)null, (File)null, (String)null, (ClassLoader)null);
throw new RuntimeException("Stub!");
}
public PathClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
super((String)null, (File)null, (String)null, (ClassLoader)null);
throw new RuntimeException("Stub!");
}
}
复制代码
嗯 能看出来 这2个都是派生自BaseDexClassLoader类,函数
public class BaseDexClassLoader extends ClassLoader {
public BaseDexClassLoader(String dexPath, File optimizedDirectory, String librarySearchPath, ClassLoader parent) {
throw new RuntimeException("Stub!");
}
protected Class<?> findClass(String name) throws ClassNotFoundException {
throw new RuntimeException("Stub!");
}
protected URL findResource(String name) {
throw new RuntimeException("Stub!");
}
protected Enumeration<URL> findResources(String name) {
throw new RuntimeException("Stub!");
}
public String findLibrary(String name) {
throw new RuntimeException("Stub!");
}
protected synchronized Package getPackage(String name) {
throw new RuntimeException("Stub!");
}
public String toString() {
throw new RuntimeException("Stub!");
}
}
复制代码
看到这可能不少人就懵逼了,这是啥意思,实际上这里表明的就是这个类执行的时候,会让ROM里的类来实际执行,这里android studio定位到的源码 只是告诉咱们,嗯 这里有一个这样的类。可是实际的实现是放在Rom中作的。 不少人到这里可能仍是没法理解是什么意思,其实这个地方在不少开源项目中都有实际用法,好比你要反射调用api里没有暴露出来给你的类怎么办呢?这个类在rom里是有的 可是api并无暴露出来给你。就能够用这种写法了。我举个滴滴开源框架VirtualApk的例子:oop
看到没有滴滴也是这么作的,将这些类放在本身的框架内暴露出来(注意包名要和ROM中的同样)这样就能够在其余地方反射调用了。 咱们随便找个源码进去看一看:
package android.app;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
/**
* @author johnsonlee
*/
public final class ActivityThread {
public static ActivityThread currentActivityThread() {
throw new RuntimeException("Stub!");
}
public static boolean isSystem() {
throw new RuntimeException("Stub!");
}
public static String currentOpPackageName() {
throw new RuntimeException("Stub!");
}
public static String currentPackageName() {
throw new RuntimeException("Stub!");
}
public static String currentProcessName() {
throw new RuntimeException("Stub!");
}
public static Application currentApplication() {
throw new RuntimeException("Stub!");
}
public ApplicationThread getApplicationThread() {
throw new RuntimeException("Stub!");
}
public Instrumentation getInstrumentation() {
throw new RuntimeException("Stub!");
}
public Looper getLooper() {
throw new RuntimeException("Stub!");
}
public Application getApplication() {
throw new RuntimeException("Stub!");
}
public String getProcessName() {
throw new RuntimeException("Stub!");
}
public final ActivityInfo resolveActivityInfo(final Intent intent) {
throw new RuntimeException("Stub!");
}
public final Activity getActivity(final IBinder token) {
throw new RuntimeException("Stub!");
}
final Handler getHandler() {
throw new RuntimeException("Stub!");
}
private class ApplicationThread extends ApplicationThreadNative {
}
}
复制代码
你看ActivityThread这个类,有过源码基础的同窗应该都知道这个类是rom里咱们api里没有这个类的。用这种方法暴露出来之后就可使用它了。
扯远了,回到正题,既然api 源码里看不到真正的实现 咱们只好去rom代码里看看了 这里推荐一个在线查看源码的网站
这里明显看出来咱们的DexClassLoader和pathClassLoader构造函数传参上面就有不一样,DexClassLoader须要提供一个额外的path路径,这个path路径咱们看下注释很容易理解:用来存放解压缩之后的dex文件。(apk和jar包解压缩均可以 只要解压缩之后的是dex文件),这个path就是解压缩的目标路径。可是PathClassLoader就没有这个构造函数。只能直接操做dex文件。 总结: DexClassLoader能够加载任何路径的apk/dex/jar PathClassLoader只能加载/data/app中的apk,也就是已经安装到手机中的apk。这个也是PathClassLoader做为默认的类加载器的缘由,由于通常程序都是安装了,在打开,这时候PathClassLoader就去加载指定的apk(解压成dex,而后在优化成odex)就能够了
继续跟源码 跟到BaseClassLoader
能够看出来BaseClassLoader的构造函数 最终是调用的DexPathList函数,注意这里2个构造函数也是分别对应的dex和path 两种classLoader的
跟到DexPathList
嗯 发现这里都是走的makeDex函数
发现了DexFile这个类,继续跟:
嗯,一直到这里,咱们发现最终的loadclass 在DexFile的 loadClassBinaryname方法完成了(这里能够和JVM中咱们自定义 的那个ClassLoader比对一下)。
有人要问既然DexFile完成的是最终classLoader须要完成的loadClass的操做,为啥不直接用dexFile呢? 看注释:
If you are not calling this from a class loader, this is most likely not going to do what you want. Use {@link Class#forName(String)} instead
这里明确说了,若是你的DexFile的loadClass操做不是在classLoader里作的,那你很大可能得不到你想要的结果。。。。
因此之后要记住了,DexFile相关的操做必定要在ClassLoader里完成
写个简单的demo
package com.example.a16040657.androidclassloader;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.v("wuyue", "MainActivity的类加载加载器:" + MainActivity.class.getClassLoader());
Log.v("wuyue", "Context的类加载加载器:" + Context.class.getClassLoader());
Log.v("wuyue", "ListView的类加载器:" + ListView.class.getClassLoader());
Log.v("wuyue", "应用程序默认加载器:" + getClassLoader());
Log.v("wuyue", "系统类加载器:" + ClassLoader.getSystemClassLoader());
Log.v("wuyue", "系统类加载器和Context的类加载器是否相等:" + (Context.class.getClassLoader() == ClassLoader.getSystemClassLoader()));
Log.v("wuyue", "系统类加载器和应用程序默认加载器是否相等:" + (getClassLoader() == ClassLoader.getSystemClassLoader()));
Log.v("wuyue", "打印应用程序默认加载器的委派机制:");
ClassLoader classLoader = getClassLoader();
while (classLoader != null) {
Log.v("wuyue", "类加载器:" + classLoader);
classLoader = classLoader.getParent();
}
Log.v("wuyue", "打印系统加载器的委派机制:");
classLoader = ClassLoader.getSystemClassLoader();
while (classLoader != null) {
Log.v("wuyue", "类加载器:" + classLoader);
classLoader = classLoader.getParent();
}
}
}
复制代码
再看看输出的结果
注意看一下咱们的listview和Context的类加载器都是bootClassLoader,很好理解,和JVM中对照一下,其实一些系统类 都是交给bootClssLoader来加载的,只不过jVM中的是叫BootstrapClassLoader罢了。都是一个意思。
注意看一下系统类加载器和应用程序加载器虽然都是pathclassloader,可是这里注意看一下 这俩的路径是不一样的。 一个是data/app 一个是sytesm/app 因此这俩是不一样的类加载器。这里要注意一下。