0

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?

IgorZ
  • 1,125
  • 3
  • 20
  • 44
  • 2
    `ID` is a constant field. – Sotirios Delimanolis Jun 09 '16 at 21:11
  • 1
    compile time constant, aka. value is inlined at the calling place (should even get converted to a single string like `System.out.println("Person ID: 12345");` - you can decompile with `javap` and see ) – zapl Jun 09 '16 at 21:22
  • That's an idea to decompile and watch it. Thanks. – IgorZ Jun 09 '16 at 21:30
  • You were right. Class is not called in that place. Instead it sets in the byte code `System.out.println("Person ID: 123456")` or: `32 ldc #13 34 invokevirtual #11 37 getstatic #2 ` – IgorZ Jun 09 '16 at 22:17

0 Answers0