Override valueof() and toString() in Java enum

前端 未结 7 1675
傲寒
傲寒 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

    You can try out this code. Since you cannot override valueOf method you have to define a custom method (getEnum in the sample code below) which returns the value that you need and change your client to use this method instead.

    public enum RandomEnum {
    
        StartHere("Start Here"),
        StopHere("Stop Here");
    
        private String value;
    
        RandomEnum(String value) {
            this.value = value;
        }
    
        public String getValue() {
            return value;
        }
    
        @Override
        public String toString() {
            return this.getValue();
        }
    
        public static RandomEnum getEnum(String value) {
            for(RandomEnum v : values())
                if(v.getValue().equalsIgnoreCase(value)) return v;
            throw new IllegalArgumentException();
        }
    }
    

提交回复
热议问题