Java enum - custom names

前端 未结 2 2020
天命终不由人
天命终不由人 2021-01-21 07:09

I want to have a Java enum whose values are integers.

For example:

public enum TaskStatus {
    TaskCreated(1), 
    TaskDeleted(2)    
}
2条回答
  •  天涯浪人
    2021-01-21 07:40

    A minimalistic answer. If the ordinal value suffices, you can do without.

    public enum TaskStatus {
        None,
        TaskCreated, 
        TaskDeleted;
    
        @Override
        public String toString() {
            // Replace upper-case with a space in front, remove the first space.
            return super.toString()
                .replaceAll("\\p{U}", " $0")
                .replaceFirst("^ ", "");
        }
    }
    

提交回复
热议问题