Override valueof() and toString() in Java enum

前端 未结 7 1614
傲寒
傲寒 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:33

    How about a Java 8 implementation? (null can be replaced by your default Enum)

    public static RandomEnum getEnum(String value) {
        return Arrays.stream(RandomEnum.values()).filter(m -> m.value.equals(value)).findAny().orElse(null);
    }
    

    Or you could use:

    ...findAny().orElseThrow(NotFoundException::new);
    
    0 讨论(0)
提交回复
热议问题