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

从上图可知,PathClassLoader构造函数传入了一个ClassLoader类型的参数parent。
PathClassLoader是何时创建以及parent是什么
从哪看呢?由于ActivityThread是我们常说的UI线程,ActivityThread类中的main()方法是整个应用的入口。所以我们来看一下ActivityThread的main()。
ActivityThread类的main方法

main方法中进行了MainLooper的初始化和主线程的创建以及主线程Handler的初始化
这里我们关注一下attach方法

在ActivityThread的attach方法中,ActivityManagerService通过attachApplication方法,将ApplicationThread对象绑定到ActivityManagerService上,mAppThread对象所对应的类是ApplicatinThread,是ActivityThread的内部类,实现了IBinder接口,用于ActivityThread和ActivityManagerService的进程间通信
我们接着看attachApplication方法

方法中调用了attachApplicationLocked方法

attachApplicationLocked方法中调用了mAppThread的bindApplication方法

bindApplication方法中创建了AppBindData对象,对象中设置了线程信息、application信息等
然后调用了sendMessage发消息,what = BIND_APPLICATION

sendMessage中封装了一下给主线程handler:mH 发消息

主线程handler的handleMessage方法中调用handleBindApplication方法


handleBindApplication方法中代码比较多,先关注两点:
1.创建了ContextImpl
2.调用了ContextImpl的getClassLoader()方法
看一下如何getClassLoader的

mClassLoader和mPackageInfo是构造函数中传入的,mClassLoader传入的是null,mPackageInfo传入的是data.info所以调用mPackageInfo.getClassLoader()

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

本文深入探讨了Android应用程序中ClassLoader的工作原理,特别是PathClassLoader及其父加载器BootClassLoader的角色。通过ActivityThread类的main方法,揭示了Class加载过程中的双亲委托机制。
423

被折叠的 条评论
为什么被折叠?



