Force Initialization of an enumerated type in Java

后端 未结 4 1222
星月不相逢
星月不相逢 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:49

    You can just reference something in the enum class. For example:

    public class EnumTest {
      static final Map map = new HashMap();
    
      enum MyEnum {
        FOO, BAR, BAZ;
    
        MyEnum() {
          map.put(name(), this);
        }
      }
      static {
        // ensure MyEnum is initialized
        MyEnum.values();
      }
    
      public static void main(String[] argsa) {
        System.out.println(map.size());
      }
    }
    

提交回复
热议问题