I guess that the answere is simple or is kind of some JVM optimization.
I don't understand why when I am calling class's static var class is not being loaded + it's static block is not working in the same time. I am trying this way:
package common;
import java.lang.reflect.Method;
public class Test {
static class Person {
public static final int ID = 12345;
static {
System.out.println("Loading " + Person.class.getName());
}
static void staticMethod() {
System.out.println("staticMethod");
}
public Person() {}
}
private static void case_1() throws Exception {
System.out.println("isLoaded: " + isLoaded("common.Test$Person"));
System.out.println("Person ID: " + Person.ID);
System.out.println("isLoaded: " + isLoaded("common.Test$Person"));
Person.staticMethod();
System.out.println("isLoaded: " + isLoaded("common.Test$Person"));
}
private static boolean isLoaded(String clazz) throws Exception {
Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
m.setAccessible(true);
ClassLoader cl = ClassLoader.getSystemClassLoader();
Object object = m.invoke(cl, clazz);
return object != null;
}
public static void main(String[] args) throws Exception {
case_1();
}
}
Output says:
isLoaded: false
Person ID: 12345
isLoaded: false
Loading common.Test$Person
staticMethod
isLoaded: true
If class is not being initialized in this case then where does JVM store this variable?