为什么PathClassLoader的父加载器(parent)是BootClassLoader?

写在前面

双亲委托机制中,当加载一个Class的时候,如果当前ClassLoader有父加载器的时候用父加载器加载。为什么PathClassLoader的父加载器(parent)是BootClassLoader?

查看PathClassLoader的源码

为什么PathClassLoader的父加载器(parent)是BootClassLoader?
从上图可知,PathClassLoader构造函数传入了一个ClassLoader类型的参数parent。

PathClassLoader是何时创建以及parent是什么
从哪看呢?由于ActivityThread是我们常说的UI线程,ActivityThread类中的main()方法是整个应用的入口。所以我们来看一下ActivityThread的main()。

ActivityThread类的main方法

为什么PathClassLoader的父加载器(parent)是BootClassLoader?
main方法中进行了MainLooper的初始化和主线程的创建以及主线程Handler的初始化
这里我们关注一下attach方法
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
在ActivityThread的attach方法中,ActivityManagerService通过attachApplication方法,将ApplicationThread对象绑定到ActivityManagerService上,mAppThread对象所对应的类是ApplicatinThread,是ActivityThread的内部类,实现了IBinder接口,用于ActivityThread和ActivityManagerService的进程间通信

我们接着看attachApplication方法
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
方法中调用了attachApplicationLocked方法
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
attachApplicationLocked方法中调用了mAppThread的bindApplication方法
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
bindApplication方法中创建了AppBindData对象,对象中设置了线程信息、application信息等
然后调用了sendMessage发消息,what = BIND_APPLICATION
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
sendMessage中封装了一下给主线程handler:mH 发消息
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
主线程handler的handleMessage方法中调用handleBindApplication方法
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
handleBindApplication方法中代码比较多,先关注两点:
1.创建了ContextImpl
2.调用了ContextImpl的getClassLoader()方法
看一下如何getClassLoader的
为什么PathClassLoader的父加载器(parent)是BootClassLoader?
mClassLoader和mPackageInfo是构造函数中传入的,mClassLoader传入的是null,mPackageInfo传入的是data.info所以调用mPackageInfo.getClassLoader()
为什么PathClassLoader的父加载器(parent)是BootClassLoader?

总结

我们写的应用程序的Class使用PathClassLoader加载,PathClassLoader的父加载器(parent)是BootClassLoader