java - 为什么Java ClassLoader加载这个类

标签 java classloader

我试图理解为什么 JVM 在看起来不需要的时候决定加载某些类。考虑以下示例代码:

public class Foo {
    public void foo() {
    }

    static class Bar {
    }

    public Bar bar() {
        return new Bar();
    }
}

当调用new Foo().foo()时,类加载器不会加载Bar,因为不需要它。但是,如果我们更改示例,让 bar 返回子类的实例:

public class Foo {    
    public void foo() {
    }

    static class Bar {
    }

    static class BigBar extends Bar {
    }

    public Bar bar() {
        return new BigBar();
    }
}

调用 new Foo().foo() 会导致类加载器加载 BarBigBar 类,即使它们都不是需要。为什么?

除了这个特定场景之外,还有什么方法可以了解 JVM 通常决定需要加载类的原因吗?

最佳答案

这是来自 Internals of Java Class Loading 的精彩读物

Whenever a new JVM is started by typing java MyMainClass, the "bootstrap class loader" is responsible for loading key Java classes like java.lang.Object and other runtime code into memory first. The runtime classes are packaged inside of the JRE\lib\rt.jar file. We cannot find the details of the bootstrap class loader in the Java documentation, since this is a native implementation. For the same reason, the behavior of the bootstrap class loader will also differ across JVMs.

In a related note, we will get null if we try to get the class loader of a core Java runtime class, like this:

log(java.lang.String.class.getClassLoader());

Next comes the Java extension class loader. We can store extension libraries, those that provide features that go beyond the core Java runtime code, in the path given by the java.ext.dirs property. The ExtClassLoader is responsible for loading all .jar files kept in the java.ext.dirs path. A developer can add his or her own application .jar files or whatever libraries he or she might need to add to the classpath to this extension directory so that they will be loaded by the extension class loader.

The third and most important class loader from the developer perspective is the AppClassLoader. The application class loader is responsible for loading all of the classes kept in the path corresponding to the java.class.path system property.

关于java - 为什么Java ClassLoader加载这个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39524402/

相关文章:

java - 从 Activity 2 到 Activity 1 进行通信并更新列表

java - 如何使用模数和指数/公钥快速破解 Java 中大量数字的 RSA 加密

java - 扩展 Java Play 框架中的默认访问第三方方法

java - JUnit类路径和ContextClassLoader不一致还是我的误解

java - 装 jar 顺序

java - 如何将 IplImage 转换为 Mat?

java - 发生 ClassCastException 但没有任何正确的详细信息

java - 将新项目添加到可扩展 ListView

scala - SBT 如何在插件任务执行中使用 Build.sbt 中的类

java - this.getClass().getResource ("").getPath() 返回不正确的路径