Android类加载ClassLoader双亲委托机制详解
一、ClassLoader类图关系
ClassLoader、BootClassLoader、BaseDexClassLoader等之间关系,如下如:
二、双亲委托机制
1、定义
如果某个类加载器在加载类时,先不会自己去尝试加载这个类,而是首将加载任务委托给父类加载器,依次递归,如果父类加载器可以完成类加载任务,就成功返回;只有父类加载器无法完成此加载任务或者没有父类加载器时,才会交给自己尝试加载。
如:可以看到创建 ClassLoader 需要接收一个 ClassLoader parent 参数。这个 parent 的目的就在于实现类加载的双亲委托
protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { // First, check if the class has already been loaded // 检查class是否有被加载 Class<?> c = findLoadedClass(name); if (c == null) { try { if (parent != null) { //如果parent不为null,则调用parent的loadClass进行加载 c = parent.loadClass(name, false); } else { //parent为null,则调用BootClassLoader进行加载 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; }
2、双亲作用
1)、避免重复加载,当父加载器已经加载了该类的时候,就没有必要子ClassLoader再加载一次。
2)、安全性考虑,防止核心API库被随意篡改。
以上就是Android类加载ClassLoader的详细内容,更多关于Android类加载ClassLoader的资料请关注脚本之家其它相关文章!
相关文章
Android checkbox的listView具体操作方法
这篇文章主要介绍了Android checkbox的listView具体操作方法,重点就是存储每个checkbox的状态值,感兴趣的小伙伴们可以参考一下2015-12-12android开发实现列表控件滚动位置精确保存和恢复的方法(推荐)
下面小编就为大家带来一篇android开发实现列表控件滚动位置精确保存和恢复的方法(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-03-03详解Android平台JSON预览(JSON-handle)
这篇文章主要介绍了Android平台JSON预览(JSON-handle),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-09-09Android Studio中CodeStyle模板的配置方式
这篇文章主要介绍了Android Studio中CodeStyle模板的配置方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-03-03
最新评论