Override valueof() and toString() in Java enum

前端 未结 7 1654
傲寒
傲寒 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:11

    Try this, but i don't sure that will work every where :)

    public enum MyEnum {
        A("Start There"),
        B("Start Here");
    
        MyEnum(String name) {
            try {
                Field fieldName = getClass().getSuperclass().getDeclaredField("name");
                fieldName.setAccessible(true);
                fieldName.set(this, name);
                fieldName.setAccessible(false);
            } catch (Exception e) {}
        }
    }
    

提交回复
热议问题