+-
java – 为什么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; 
        } catch(Throwable e) {
            e.printStackTrace();
        }
    }   
}
最佳答案
这些问题的答案通常都隐藏在规范…… (§12.4.2)中

初始化类时会发生什么:

步骤1-4与此问题有些无关.这里的第5步是触发异常的原因:

5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError.

6-8继续初始化,8执行初始化器,通常发生的是在步骤9:

9. If the execution of the initializers completes normally, then lock this Class object, label it fully initialized, notify all waiting threads, release the lock, and complete this procedure normally.

但是我们在初始化程序中出错了所以:

10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.

是的,我们看到空指针异常的ExceptionInInitializerError b / c.

11. Lock the Class object, label it erroneous, notify all waiting threads, release the lock, and complete this procedure abruptly with reason E or its replacement as determined in the previous step. (Due to a flaw in some early implementations, a exception during class initialization was ignored, rather than causing an ExceptionInInitializerError as described here.)

然后该类被标记为错误,这就是我们第二次从第5步获得异常的原因.

The surprising part is the third printout which shows that TestClass.class in MainClass actually holds a reference to a physical Class object.

可能因为TestClass仍然存在,它只是标记为错误.它已经加载并验证.

点击查看更多相关文章

转载注明原文:java – 为什么NoClassDefFoundError由静态字段初始化失败引起? - 乐贴网