Java静态变量和类加载

时间:2016-06-09 20:54:53

标签: java

我认为回答很简单或者是一些JVM优化 我不明白为什么当我调用类的静态var类没有被加载+它的静态块不能同时工作。我这样想:

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();
  }
}

输出说:

isLoaded: false
Person ID: 12345
isLoaded: false
Loading common.Test$Person
staticMethod
isLoaded: true

如果在这种情况下没有初始化类,那么JVM在哪里存储这个变量?

0 个答案:

没有答案