Can someone explain me the difference between Class.forName() and Thread.currentThread().getContextClassLoader().loadClass().
I have next code
<code>
public class Test {
static {
System.out.println("Hello from static block");
}
}
public class Application {
public static void main(String[] args) throws ClassNotFoundException {
//Class test = Class.forName("com.home.Test"); //Outputs "Hello from static block"
Thread.currentThread().getContextClassLoader().loadClass("com.home.Test");
}
}
</code>
And when i execute Class.forName(“com.home.Test”) it outputs “Hello from static block”. But when i execute Thread.currentThread().getContextClassLoader().loadClass(“com.home.Test”); it outputs nothing.
ClassLoader.loadClass(String)does not resolve the class (and thus does not initialize it either).Class.forName(String)on the other hand does initialize the class. This is why you see the initializers being run in that case, but not when usingloadClass.The load/link/initialize steps are described in the JSL in the Excecution section if you want the details (it’s an interesting read).