I am attempting to find a way to force Java to load/initialize an enumerated type (which is nested within a class that contains a static Map).
This is important to me be
Seems like this is exactly why it is often recommended to use accessor methods instead of directly referencing members. Your problem is that the code allows access to the map before it is initialized. Block arbitrary access to the map, and hide it behind an accessor method that makes sure it is initialized.
import java.util.Map;
import java.util.HashMap;
public enum EnumTest {
FOO, BAR, BAZ;
private static Map map = null;
public synchronized static Map getMap() {
if (map == null) {
map = new HashMap();
for ( EnumTest e : EnumTest.values() ) {
map.put( e.name(), e );
}
}
return map;
}
public static void main(String[] args) {
System.out.println( EnumTest.getMap().size() );
}
}