安卓高手之路之ClassLoader(三)
发布日期:2021-09-08 22:55:07 浏览次数:11 分类:技术文章

本文共 1652 字,大约阅读时间需要 5 分钟。

由于看C++和C代码看得很累,很辛苦。上一章终于解脱到java代码中来了。 第一个getClassLoader发生在main的preload方法中,

 

public static void main(String argv[]) {

 preload();

}

Java代码  
  1. static void preload() {  
  2.     preloadClasses();  
  3.     preloadResources();  
  4. }  

 

Java代码  
  1. private static void preloadClasses() {  
  2.        final VMRuntime runtime = VMRuntime.getRuntime();  
  3.   
  4.        InputStream is = ZygoteInit.class.getClassLoader().getResourceAsStream(  
  5.                PRELOADED_CLASSES);  

 可以看到,直接调用了getClassLoader()这个classLoader是个什么东西呢。

 

Java代码  
  1. public ClassLoader getClassLoader() {  
  2.        if (this.isPrimitive()) {  
  3.            return null;  
  4.        }  
  5.   
  6.        ClassLoader loader = getClassLoaderImpl();  
  7.        if (loader == null) {  
  8.            loader = BootClassLoader.getInstance();  
  9.        }  
  10.        return loader;  
  11.    }  

 由于这个类是没有classloader的,因此调用的是BootClassLoader.getInstance().

  

Java代码  
  1. /** 
  2.  * Provides an explicit representation of the boot class loader. It sits at the 
  3.  * head of the class loader chain and delegates requests to the VM's internal 
  4.  * class loading mechanism. 
  5.  */  
  6. class BootClassLoader extends ClassLoader {  

 

现在明白了吧。BootClassLoader原来就是第一个class的ClassLoader。对于Zygote是com.android.internal.os.ZygoteInit,对于其他的,那就是com.android.internal.os.RuntimeInit 的classloader。也就是init.rc中指定的BOOTCLASSPATH指定的classLoader。

现在看另外一个方法也就是RuntimeInit 的加载

Java代码  
  1. const char* envStr = getenv("CLASSPATH");  
  2.    if (envStr != NULL) {  
  3.        gDvm.classPathStr = strdup(envStr);  
  4.    } else {  
  5.        gDvm.classPathStr = strdup(".");  
  6.    }  

 

Java代码  
  1. handleChildProc  

 

Java代码  
  1. else {  
  2.                     cloader = ClassLoader.getSystemClassLoader();  
  3.                 }  
  4.   
  5.                 try {  
  6.                     ZygoteInit.invokeStaticMain(cloader, className, mainArgs);  

 

 ClassLoader.getSystemClassLoader();这个classLoader与普通的classLoader又有不同。这个是一个PathClassLoader 这个以BootClassLoader作为父Loader。这很明显是一个装饰者模式。

转载于:https://www.cnblogs.com/xiaochao1234/p/4174467.html

转载地址:https://blog.csdn.net/weixin_34341229/article/details/93389234 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:git常用命令 (阿里云code)
下一篇:汇编基础教程(二)——常用汇编指令之运算指令

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月20日 05时57分37秒