问题描述
这是一个有趣的java问题。
Here is a interesting java question.
以下简单java程序包含静态方法初始化的静态字段。实际上,我强制计算intiailize值的方法引发NullPointException,当我访问这样的静态字段时,会引发NoClassDefFoundError。似乎VM对待Class并不完整。
the following simple java program contains static field initialized by a method statically. Actually, I force the method which calculate the intiailize value to raise a NullPointException, When I access such a static field, a NoClassDefFoundError will raised. it seems the VM treat the Class is not complete.
但是当我访问Class时,它仍然可用;
But when I access the Class, it still available;
有谁知道为什么?
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();
}
}
}
推荐答案
这些问题的答案通常都隐藏在规范中......
The answer to such questions is usually buried somewhere in the specs... (§12.4.2)
初始化类时会发生什么:
What happens when classes are initialized:
步骤1-4与此问题有些无关。这里的第5步是触发异常的原因:
Steps 1-4 are somewhat unrelated to this question. Step 5 here is what triggers the exception:
6-8继续初始化,8执行初始值设定项,通常在步骤9中执行:
6-8 continue the initialization, 8 executes the initializers, and what usually happens is in step 9:
但我们在初始化程序中出错:
But we got an error in the initializer so:
是的,我们看到 ExceptionInInitializerError
b / c的空指针异常。
Yep, we see an ExceptionInInitializerError
b/c of the null pointer exception.
然后该类被标记为错误,这就是我们第二次从第5步获得例外的原因。
And then the class is marked erroneous which is why we get the exception from step 5 the second time.
可能是因为 TestClass
仍然存在,它只是标记为错误。它已经加载并验证。
Probably because TestClass
still exists, it's just marked erroneous. It has been already loaded and verified.
这篇关于为什么NoClassDefFoundError由静态字段初始化失败引起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!