When a constructor uses a reference to a constant that is being lazily instantiated, java throws an ExceptionInInitializerError (specifically on the line “this(ClassA.INSTANCE1)”).
public class ClassA {
public static final ClassA INSTANCE1 = get("INSTANCE1");
public static final ClassA INSTANCE2 = get("INSTANCE2");
private static final Map<String, ClassA> MULTITON_MAP = new HashMap<String, ClassA>();
private String name;
private ClassA(String name) {
this.name = name;
}
public static ClassA get(String name) {
ClassA toReturn = MULTITON_MAP.get(name);
if (toReturn == null) {
toReturn = new ClassA(name);
MULTITON_MAP.put(name, toReturn);
}
return toReturn;
}
}
public class ClassB {
private ClassA type;
public ClassB() {
this(ClassA.INSTANCE1);
}
public ClassB(ClassA type) {
this.type = type;
}
public static void main(String[] args) {
new ClassB();
}
}
I’ve solved the problem by removing the lazy instantiation and moving instantiations into a static block.
public class ClassA {
public static final ClassA INSTANCE1;
public static final ClassB INSTANCE2;
...
static {
INSTANCE1 = new ClassA("INSTANCE1");
INSTANCE2 = new ClassA("INSTANCE2");
MULTITON_MAP.put("INSTANCE1", INSTANCE1);
MULTITON_MAP.put("INSTANCE2", INSTANCE2);
}
...
}
So, my question is, why is Java unable to handle what I did previously. What causes the error and why?
Thanks a bunch!
I think your problem is that you are trying to initialize
INSTANCE1beforeMULTITON_MAP, but the instantiation ofINSTANCE1depends onMULTITON_MAP.E.g. when you call
MULTITON_MAP.get(name);inget,MULTITON_MAPis still null.