发布于 2014-08-04 14:49:01
Field#set(Object, Object)
可用于设置static
字段。如果尝试对统一类的字段进行set
,JVM将首先尝试初始化类。如果发生故障,set
将抛出一个ExceptionInInitializerError
。见下面的例子:
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
}
}
https://stackoverflow.com/questions/25121294
复制相似问题