When can Field.set(Object obj, Object value) throw

2019-07-31 10:37发布

问题:

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
    }
}