1

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?

NuCradle
  • 665
  • 1
  • 9
  • 31
  • Have a look at - https://stackoverflow.com/questions/38433869/nullpointerexception-this-inside-enum-constructor-causing-npe – Thiyagu Jun 16 '19 at 02:50
  • 2
    What are you trying to achieve here? `valueOf` already exists. Usually `toString`, `valueOf` and `ordinal` achieve most use cases for `enum`. – DCTID Jun 16 '19 at 03:58
  • @user7 So as long as I don't dereference a static property, the above should be fine. – NuCradle Jun 17 '19 at 13:12
  • @DCTID I am trying to demarshall JSON values to their correspoding `MyEnum` during Spring RESTful call, and since it returns a JSON enum value, I need to have this `Map` to convert that `String value` using `forValue()`, annoted with Jackson's `@JsonCreator`. (for brevity, I excluded JSON stuff and other `MyEnum` parameters to focus on the main issue). – NuCradle Jun 17 '19 at 13:16

2 Answers2

2

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

}
Abhishek Garg
  • 2,158
  • 1
  • 16
  • 30
0

build map at runtime:

public enum MyEnum {
    FIRST_ENUM("first enum"),SECOND_ENUM("second enum"),THIRD_ENUM("third enum"),FORTH_ENUM("forth enum");
    private final String param;
    MyEnum(String param) {
        this.param=param;
    }
    static void build() {
        for(MyEnum myEnum:MyEnum.values())
            map.put(myEnum.param,myEnum);
    }
    public static void main(String[] arguments) {
        MyEnum.build();
        System.out.println(map);
    }
    private static Map<String,MyEnum> map=new HashMap<>();
}
Ray Tayek
  • 9,841
  • 8
  • 50
  • 90