gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:29:52 24 4
gpt4 key购买 nike

我试图理解为什么 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com