peter.petrov
peter.petrov

Reputation: 39477

Java enum - custom names

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

For example:

public enum TaskStatus {
    TaskCreated(1), 
    TaskDeleted(2)    
}

But I also want custom names for these two constants like
e.g. "Task Created" and "Task Deleted" (with spaces there).
I want to do it as elegantly as possible without writing
too much additional code.

Can I achieve this without an additional map which
maps the enum constants to their custom names?

I am using JDK 6 in this project.

Upvotes: 4

Views: 8866

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1504162

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.

Upvotes: 17

Joop Eggen
Joop Eggen

Reputation: 109623

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("^ ", "");
    }
}

Upvotes: 4

Related Questions