Is It Safe to Put a Java Enum in a Static Map During Its Construction Call?

NuCradle picture NuCradle · Jun 16, 2019 · Viewed 8.4k times · Source

As the title reads, I have the following Enum:

public enum MyEnum {

  FIRST_ENUM("first enum"),
  SECOND_ENUM("second enum"),
  THIRD_ENUM("third enum"),
  FORTH_ENUM("forth enum");

  private final String param;

  private static class Mapper {
    static Map<String, MyEnum> MAP = new HashMap<>();
  }

  MyEnum(String param) {
    this.param = param;
    Mapper.MAP.put(param, this); // Is this going to be a problem?
  }

  public static MyEnum MyEnum(String value) {
    return Holder.MAP.get(value);
  }

}

I would like to know if putting an enum that its instantiation/construction hasn't been completed could possibly cause an issue?

Answer

Abhishek Garg picture Abhishek Garg · Jul 27, 2019

You don't need to create a separate Mapper class. We use something similar for our use case also.

public enum MyEnum {

    FIRST_ENUM("first enum"),
    SECOND_ENUM("second enum"),
    THIRD_ENUM("third enum"),
    FORTH_ENUM("forth enum");

    private final String param;
    private static final Map<String, MyEnum> MAP = new HashMap<>();
    static {

        for (final MyEnum myEnum : MyEnum.values()) {
            MAP.put(myEnum.param, myEnum);
        }
    }

    MyEnum(String param) {
        this.param = param;
    }

    @JsonCreator
    public static MyEnum myEnumMapper(String value) {
        return MAP.get(value);
    }

}