Java enum - custom names

前端 未结 2 2019
天命终不由人
天命终不由人 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.

    0 讨论(0)
  • 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("^ ", "");
        }
    }
    
    0 讨论(0)
提交回复
热议问题