Force Initialization of an enumerated type in Java

后端 未结 4 1213
星月不相逢
星月不相逢 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 02:03

    A class is loaded when you reference a class. This works the same for all classes.

    The problem you have is more likely to be that an Enum value is initialised before any static block. i.e. you cannot refer to something initialise in a static block in a constructor. (Generally initialising static content in a constructor is a BAD idea) You need to initialise the Map in the static block, not the constructor.

    Try

    import java.util.Map; 
    import java.util.HashMap; 
    
    public enum EnumTest { 
      FOO, BAR, BAZ; 
    
      private static final Map map = new LinkedHashMap(); 
      static { 
          for(EnumTest e : EnumTest.values())
            map.put(e.name(), e); 
      } 
    
      public static void main(String... args) { 
        System.out.println(EnumTest.map); 
      } 
    }
    

提交回复
热议问题