Search code examples
javaclassloaderdynamic-class-loaders

boolean initialize parameter of class.forName method in java


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?


Solution

  • 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.