3

Although I read the documentation, I'm not able to understand what is the difference here between those two lines of java codee when loading a class:

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


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

here the boolean parameter is explained in the documentation as follows:

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

In my case, even if i use the code with false parameter, it still works. So I wanted to know when it should be true then?

Ahmet Eroğlu
  • 594
  • 1
  • 7
  • 23
  • The class is initialized only if the initialize parameter is true and if it has not been initialized earlier. – Ali Beyit Dec 20 '19 at 10:36
  • 2
    Maybe https://stackoverflow.com/questions/13739726/class-way-of-obtaining-class-does-it-initialize-the-class would be helpful for you – Spiros batzio Dec 20 '19 at 10:40

1 Answers1

10

As the referenced chapter of the JLS states:

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.

So the first call would not run any static initializers for fields and constants like private static String x = "this is my value"; leaving x null and to be initialized later, whicle the second one would set x to the desired value.

Creating an object from this class is the latest point where the JVM will initialize the class on its own, if this was skipped until then.

Nicktar
  • 5,548
  • 1
  • 28
  • 43
  • 1
    Actually, `private String x` would not be affected, since it’s an instance field. `private static String x`, however, would be affected. Also there will never be a time when `x` is seen as null, because reading `x` would require the class being initialized. – VGR Dec 20 '19 at 16:13
  • 1
    It’s misleading to label “creating an object from this class” as the “latest point” of class initialization. As @VGR already said, you’ll never perceive the field `x` to be `null` outside of a class initializer, as accessing a `static` field of the class will trigger its initialization as well. [All possible triggers are explicitly specified](https://stackoverflow.com/a/50347325/2711488). – Holger Feb 11 '20 at 16:27