Force Initialization of an enumerated type in Java

后端 未结 4 1156
星月不相逢
星月不相逢 2021-02-20 01:46

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

4条回答
  •  [愿得一人]
    2021-02-20 01:54

    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() );
      }
    }
    

提交回复
热议问题