聊一聊JVM的类加载器机制

原文链接:https://mp.weixin.qq.com/s/PeFTuJmQhqzFIB-FFhmtgw

聊一聊JVM的类加载器机制

目录

聊一聊JVM的类加载器机制

01 怎么获取类加载器?哪几种类加载器

02 各个加载器加载的路径?

 


01 怎么获取类加载器?哪几种类加载器

  • BootStrapClassLoader 引导类加载器
  • ExtClassLoader       扩展类加载器

  • AppClassLoader       应用级别的类加载器

  • UserDefineClassLoader 用户自定义的类加载器

    Launcher launcher = Launcher.getLauncher();
    log.info("JVM启动器有两种类加载器:");
    log.info("1.Launcher-AppClassLoader:{}", launcher.getClassLoader());
    log.info("2.Launcher-ExtClassLoader:{}", launcher.getClassLoader().getParent());
    log.info("3.Launcher-BootStrapClassLoader(由c++实现,无法访问):{}", launcher.getClassLoader().getParent().getParent());

     

 


 

02 各个加载器加载的路径?  

        log.info("--------------No1.BootstrapClassLoader(引导类加载器)加载${JAVA_HOME}/jre/lib下的jar--------------");
        URL[] urls = Launcher.getBootstrapClassPath().getURLs();
        for (URL url : urls)
            log.info(url.getPath());
        log.info("--------------------------------------------------------");

        log.info("--------------No2.ExtClassLoader(系统扩展类加载器)加载${JAVA_HOME}/jre/lib/ext下的jar--------------");

        URLClassLoader extClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader().getParent();
        printUrl(extClassLoader);
        log.info("--------------------------------------------------------");

        log.info("--------------No3.AppClassLoader(应用级别的类加载器)加载classPath下的jar--------------");
        URLClassLoader appClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        printUrl(appClassLoader);
        log.info("--------------------------------------------------------");

 

private static void printUrl(URLClassLoader appClassLoader) {

URL[] urls;
log.info(appClassLoader.toString());
urls = appClassLoader.getURLs();
for (URL url : urls)
log.info(url.getPath());

}

 

获取一个系统的启动器,通过启动器获取类加载器,用来将class文件加载到内存中;

类加载器的实现机制,是基于双亲委托模型实现的,意味着

1 AppClassLoader加载不到的类,会往父哪里ExtClassLoader的去加载2 ExtClassLoader加载不到的类,会再往上级BootStrapClassLoader中去加载3 BootStrapClassLoader记载不到的类,会抛出ClassNotFound似的异常


展开阅读全文

没有更多推荐了,返回首页