小编ext*_*xt2的帖子

为什么NoClassDefFoundError由静态字段初始化失败引起?

这是一个有趣的java问题.

以下简单的java程序包含静态方法初始化的静态字段.实际上,我强制计算intiailize值的方法引发NullPointException,当我访问这样的静态字段时,会引发NoClassDefFoundError.似乎VM对待Class并不完整.

但是当我访问Class时,它仍然可用;

有谁知道为什么?

class TestClass {
    public static TestClass instance = init();

    public static TestClass init() {
       String a = null;
       a.charAt(0); //force a null point exception;
       return new TestClass();
    }
}

class MainClass {
    static public void main(String[] args) {
       accessStatic(); // a ExceptionInInitializerError raised cause by NullPointer
       accessStatic(); //now a NoClassDefFoundError occurs;

       // But the class of TestClass is still available; why?
       System.out.println("TestClass.class=" + TestClass.class);
    }

    static void accessStatic() {
        TestClass a;

        try {
            a = TestClass.instance; …
Run Code Online (Sandbox Code Playgroud)

java static initialization noclassdeffounderror

34
推荐指数
2
解决办法
2万
查看次数