Override valueof() and toString() in Java enum

前端 未结 7 1642
傲寒
傲寒 2020-12-02 12:36

The values in my enum are words that need to have spaces in them, but enums can\'t have spaces in their values so it\'s all bunched up. I want to override

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 13:07

    The following is a nice generic alternative to valueOf()

    public static RandomEnum getEnum(String value) {
      for (RandomEnum re : RandomEnum.values()) {
        if (re.description.compareTo(value) == 0) {
          return re;
        }
      }
      throw new IllegalArgumentException("Invalid RandomEnum value: " + value);
    }
    

提交回复
热议问题