java 中 class.forName 方法的布尔初始化参数

boolean initialize parameter of class.forName method in java

虽然我阅读了文档,但在加载 class:

时,我无法理解这两行 java codee 之间的区别
Class<?> cls = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror", false, enginClassLoader);


Class<?> cls = Class.forName("jdk.nashorn.api.scripting.ScriptObjectMirror", true, enginClassLoader);

这里boolean参数在文档中解释如下:

initialize if true the class will be initialized. See Section 12.4 of The Java Language Specification.

在我的例子中,即使我使用带有 false 参数的代码,它仍然有效。所以我想知道什么时候应该是真的?

正如 JLS 的参考章节所述:

Initialization of a class consists of executing its static initializers and the initializers for static fields (class variables) declared in the class.

Initialization of an interface consists of executing the initializers for fields (constants) declared in the interface.

Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class are not initialized. Similarly, the superinterfaces of an interface are not initialized before the interface is initialized.

所以第一个调用不会 运行 字段和常量的任何静态初始值设定项,例如 private static String x = "this is my value"; 留下 x null 并稍后进行初始化,而第二个调用会将 x 设置为所需的值。

从这个 class 创建一个对象是 JVM 将自己初始化 class 的最后一点,如果这之前被跳过的话。