详解Android类加载ClassLoader

所属分类: 软件编程 / Android 阅读数: 40
收藏 0 赞 0 分享

基本知识

Java的类加载设计了一套双亲代理的模式,使得用户没法替换系统的核心类,从而让应用更安全。所谓双亲代理就是指,当加载类的时候首先去Bootstrap中加载类,如果没有则去Extension中加载,如果再没有才去AppClassLoader中去加载。从而实现安全和稳定。

Java ClassLoader

BootstrapClassLoader

引导类加载器 ,用来加载Java的核心库。通过底层代码来实现的,基本上只要parent为null,那就表示引导类加载器。

比如:charsets.jar、deploy.jar、javaws.jar、jce.jar、jfr.jar、jfxswt.jar、jsse.jar、management-agent.jar、plugin.jar、resources.jar、rt.jar

ExtClassLoader

拓展类加载器 ,用来加载Java的拓展的类库, ${JAVA_HOME}/jre/lib/ext/ 目录中的所有jar。

比如:cldrdata.jar、dnsns.jar、jfxrt.jar、localedata.jar、nashorn.jar、sunec.jar、sunjce_provider.jar、sunpkcs11.jar、zipfs.jar等等

AppClassLoader

系统类加载器 (不要被名字给迷惑),用来加载Java应用中的类。一般来说自己写的类都是通过这个加载的。而Java中 ClassLoader.getSystemClassLoader() 返回的就是AppClassLoader。(Android中修改了ClassLoader的逻辑,返回的会是一个PathClassLoader)

自定义ClassLoader

用户如果想自定义ClassLoader的话,只需要继承自 java.lang.ClassLoader 即可。

ClassLoader中与加载类相关的方法:

  1. getParent() 返回该类加载器的父类加载器。
  2. loadClass(String name) 加载名称为 name的类,返回的结果是 java.lang.Class类的实例。
  3. findClass(String name) 查找名称为 name的类,返回的结果是 java.lang.Class类的实例。
  4. findLoadedClass(String name) 查找名称为 name的已经被加载过的类,返回的结果是 java.lang.Class类的实例。
  5. defineClass(String name, byte[] b, int off, int len) 把字节数组 b中的内容转换成 Java 类,返回的结果是 java.lang.Class类的实例。这个方法被声明为 final的。

也许你不太了解上面几个函数的区别,没关系,我们来看下源码是如何实现的。

//ClassLoader.java
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) {
      long t0 = System.nanoTime();
      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.
        long t1 = System.nanoTime();
        c = findClass(name);

        // this is the defining class loader; record the stats
      }
    }
    return c;
}

所以优先级大概如下:

loadClass → findLoadedClass → parent.loadClass/findBootstrapClassOrNull → findClass → defineClass

Android ClassLoader

在Android中ClassLoader主要有两个直接子类,叫做 BaseDexClassLoader 和 SecureClassLoader 。而前者有两个直接子类是 PathClassLoader 和 DexClassLoader (Android O添加了 InMemoryDexClassLoader ,略)。

我们只讨论PathClassLoader和DexClassLoader

PathClassLoader

用来加载安装了的应用中的dex文件。它也是Android里面的一个最核心的ClassLoader了。相当于Java中的那个AppClassLoader。

public class PathClassLoader extends BaseDexClassLoader {
  /**
   * Creates a {@code PathClassLoader} that operates on a given list of files
   * and directories. This method is equivalent to calling
   * {@link #PathClassLoader(String, String, ClassLoader)} with a
   * {@code null} value for the second argument (see description there).
   *
   * @param dexPath the list of jar/apk files containing classes and
   * resources, delimited by {@code File.pathSeparator}, which
   * defaults to {@code ":"} on Android
   * @param parent the parent class loader
   */
  public PathClassLoader(String dexPath, ClassLoader parent) {
    super(dexPath, null, null, parent);
  }

  /**
   * Creates a {@code PathClassLoader} that operates on two given
   * lists of files and directories. The entries of the first list
   * should be one of the following:
   *
   * <ul>
   * <li>JAR/ZIP/APK files, possibly containing a "classes.dex" file as
   * well as arbitrary resources.
   * <li>Raw ".dex" files (not inside a zip file).
   * </ul>
   *
   * The entries of the second list should be directories containing
   * native library files.
   *
   * @param dexPath the list of jar/apk files containing classes and
   * resources, delimited by {@code File.pathSeparator}, which
   * defaults to {@code ":"} on Android
   * @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 PathClassLoader(String dexPath, String librarySearchPath, ClassLoader parent) {
    super(dexPath, null, librarySearchPath, parent);
  }
}

它的实例化是通过调用 ApplicationLoaders.getClassLoader 来实现的。

它是在ActivityThread启动时发送一个BIND_APPLICATION消息后在handleBindApplication中创建ContextImpl时调用LoadedApk里面的 getResources(ActivityThread mainThread) 最后回到ActivityThread中又调用LoadedApk的 getClassLoader 生成的,具体的在LoadedApk的 createOrUpdateClassLoaderLocked

那么问题来了,当Android加载class的时候,LoadedApk中的ClassLoader是怎么被调用到的呢?

其实Class里面,如果你不给ClassLoader的话,它默认会去拿Java虚拟机栈里面的 CallingClassLoader ,而这个就是LoadedApk里面的同一个ClassLoader。

//Class.java
public static Class<?> forName(String className)
      throws ClassNotFoundException {
  return forName(className, true, VMStack.getCallingClassLoader());
}

查看VMStack的源码发现 getCallingClassLoader 其实是一个native函数,Android通过底层实现了这个。

//dalvik.system.VMStack
/**
 * Returns the defining class loader of the caller's caller.
 *
 * @return the requested class loader, or {@code null} if this is the
 *     bootstrap class loader.
 */
@FastNative
native public static ClassLoader getCallingClassLoader();

底层想必最终也是拿到LoadedApk里面的ClassLoader。

DexClassLoader

它是一个可以用来加载包含dex文件的jar或者apk文件的,但是它可以用来加载非安装的apk。比如加载sdcard上面的,或者NetWork的。

public class DexClassLoader extends BaseDexClassLoader {
  /**
   * Creates a {@code DexClassLoader} that finds interpreted and native
   * code. Interpreted classes are found in a set of DEX files contained
   * in Jar or APK files.
   *
   * <p>The path lists are separated using the character specified by the
   * {@code path.separator} system property, which defaults to {@code :}.
   *
   * @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; must not 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 DexClassLoader(String dexPath, String optimizedDirectory,
      String librarySearchPath, ClassLoader parent) {
    super(dexPath, new File(optimizedDirectory), librarySearchPath, parent);
  }
}

比如现在很流行的插件化/热补丁,其实都是通过DexClassLoader来实现的。具体思路是: 创建一个DexClassLoader,通过反射将前者的DexPathList跟系统的PathClassLoader中的DexPathList合并,就可以实现优先加载我们自己的新类,从而替换旧类中的逻辑了。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

Android控件系列之CheckBox使用介绍

CheckBox和Button一样,也是一种古老的控件,它的优点在于,不用用户去填写具体的信息,只需轻轻点击,缺点在于只有“是”和“否”两种情况,但我们往往利用它的这个特性,来获取用户的一些信息
收藏 0 赞 0 分享

Android控件系列之EditText使用方法

EditText是接受用户输入信息的最重要控件。通过前面课程的学习,您可能会猜到可以利用EditText.getText()获取它的文本,但真正的项目中,可能没那么简单,需要更多的限制,如文本长度限制,是否数字限制等等
收藏 0 赞 0 分享

Android控件系列之TextView使用介绍

TextView类似一般UI中的Label,TextBlock等控件,只是为了单纯的显示一行或多行文本,本文介绍了Android中文本控件TextView的用法和常用属性的用法
收藏 0 赞 0 分享

asynctask的用法详解

Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行,本文将为您介绍asynctask的用法
收藏 0 赞 0 分享

Android开发 旋转屏幕导致Activity重建解决方法

Android开发文档上专门有一小节解释这个问题。简单来说,Activity是负责与用户交互的最主要机制,接下来为您详细介绍
收藏 0 赞 0 分享

Notification与NotificationManager详细介绍

在Android系统中,发一个状态栏通知还是很方便的。下面我们就来看一下,怎么发送状态栏通知,状态栏通知又有哪些参数可以设置
收藏 0 赞 0 分享

android LinearLayout和RelativeLayout组合实现精确布局方法介绍

用android LinearLayout和RelativeLayout实现精确布局此方法适合很适合新人看
收藏 0 赞 0 分享

android listview优化几种写法详细介绍

这篇文章只是总结下getView里面优化视图的几种写法,需要的朋友可以参考下
收藏 0 赞 0 分享

Android应用开发SharedPreferences存储数据的使用方法

SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据
收藏 0 赞 0 分享

Android之PreferenceActivity应用详解

为了引入这个概率 首先从需求说起 即:现有某Activity专门用于手机属性设置 那么应该如何做呢
收藏 0 赞 0 分享
查看更多