The javadoc for the set method of Fieldclass clearly states that ExceptionInInitializerError may occur if the initialization provoked by this method fails. I was wondering that Classes get lazily initialized when they are referenced or when we use Class.forName("binary name",true,ClassLoader) .if initialization of class does not fail,then class variables have been initialized according to the value assigned in the declaration or as in static constructor.Once a field has been initliazed ,can it explicity throw ExceptionInInitializerError when called by the Field's class set method??
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Field#set(Object, Object)
can be used to set static
fields. If you try to set
the field of an unitialized class, the JVM will first try to initialize the class. If a failure occurs, then set
will throw a ExceptionInInitializerError
. See the example below:
public class Example {
public static void main(String[] args) throws Exception {
Field field = Fail.class.getDeclaredField("number");
field.set(null, 42); // Fail class isn't initialized at this point
}
}
class Fail {
static int number;
static {
boolean val = true;
if (val)
throw new RuntimeException(); // causes initialization to end with an exception
}
}