How does class loading work in Java, and what are the three stages?
Loading a class in Java happens in three stages, and each one has its own job.
The first stage is loading. The class loader finds the bytes of the class file and makes a runtime class object out of them. Where the bytes come from is the loader's business. It could be a folder of class files, a jar file, a network location, or even bytes that your program generated.
The second stage is linking. This has three parts of its own. The class is verified, which means that the virtual machine checks that the bytecode is safe and follows the rules. The class is prepared, which means that the static fields are created and given their default values. And the class is resolved, which means that the references it makes to other classes are looked up.
The third stage is initialisation. This is where the static initialiser blocks run and the static fields are given their real values. This happens after the class has been loaded and linked, and it happens exactly once.
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> c = Main.class;
System.out.println("name : " + c.getName());
System.out.println("simple name : " + c.getSimpleName());
System.out.println("the loader : " + c.getClassLoader().getName());
System.out.println("the parent : " + c.getClassLoader().getParent().getName());
// Loading a class by name, if it is not loaded already.
Class<?> loaded = Class.forName("java.lang.String");
System.out.println("the same class : " + (loaded == String.class));
// Every class has one class object, however it is reached.
System.out.println("one class object : " + (Main.class == c));
}
}
So the answer to the question is this. The three stages are loading, linking and initialisation, and they happen in that order and only once for each class.
The next question in this topic looks at the rule that decides where a class comes from.