Java enum - custom names

前端 未结 2 2018
天命终不由人
天命终不由人 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:26

    Just add a field for that:

    public enum TaskStatus {
        TaskCreated(1, "Task Created"), 
        TaskDeleted(2, "Task Deleted");
    
        private final int value;
        private final String description;
    
        private TaskStatus(int value, String description) {
            this.value = value;
            this.description = description;
        }
    
        // Getters etc
    
        // Consider overriding toString to return the description
    }
    

    If you don't want to specify the string, and just want to add a space before each capital letter, that's feasible as well - but personally I'd stick with the above approach for simplicity and flexibility. (It separates the description from the identifier.)

    Of course if you want i18n, you should probably just use the enum value name as a key into a resource file.

提交回复
热议问题