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??
Asked
Active
Viewed 217 times
1 Answers
5
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
}
}

Sotirios Delimanolis
- 274,122
- 60
- 696
- 724
-
So the static initilizer block throws the exception but since the caller of the method is Field class's set method,it throws the exception?? – Kumar Abhinav Aug 04 '14 at 14:52
-
@kumar That is correct. (In actuality, I think the method catches it and rethrows it.) – Sotirios Delimanolis Aug 04 '14 at 15:03