Hi stackoverflow members, Here is a little question related to the actual meaning of "class loading time".
For example the following code:
public class Sequence {
Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
System.out.println("Indeed");
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static { System.out.println("x "); }
}
It does print out first "x" which is static so the static init blocks are always loaded at "class loading time". I get it, but do you know exactly when this loading time happens? I thought when the class first gets called in the main method by creating the first object but in that case the result should have been different by printing out first "Indeed". Anyone can help me clarifying this doubt? I have checked other post talking about this argument in general but still I think would be much clearer (at least for me) getting to know when exactly, in the code reported above, the "class loading time" happens.
Thanks in advance.
Java ClassLoader is used to load the classes at run time. In other words, JVM performs the linking process at runtime. Classes are loaded into the JVM according to need. If a loaded class depends on another class, that class is loaded as well. When we request to load a class, it delegates the class to its parent.
Loading involves obtaining the byte array representing the Java class file. Verification of a Java class file is the process of checking that the class file is structurally well-formed and then inspecting the class file contents to ensure that the code does not attempt to perform operations that are not permitted.
2 Answers. Save this answer. Show activity on this post. A classloader can only actually load a class once!
Classloading is done by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazy load the class until a need for class initialization occurs. If Class is loaded before it's actually being used it can sit inside before being initialized.
The answer to your question is in the JLS Chapter 12.4.1 When Initialization Occurs
A class or interface type
T
will be initialized immediately before the first occurrence of any one of the following:
T
is a class and an instance ofT
is created.T
is a class and a static method declared byT
is invoked.- A static field declared by
T
is assigned.- A static field declared by
T
is used and the field is not a constant variable (§4.12.4).T
is a top level class (§7.6), and an assert statement (§14.10) lexically nested withinT
(§8.1.3) is executed.
I recommend you start reading a few lines above at JLS Chapter 12.4. Initialization of Classes and Interfaces
Just start with Chapter 12. Execution, it exactly describes when a class needs to be loaded. The initialization will be done after loading it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With