spacebiker spacebiker - 3 months ago 41
Java Question

Print Java ENUM to lower case by default keeping enum constants in uppercase

I have an ENUM in JAVA i'd like to serialize, so that when i call it from anywhere in the code i get the lowercase representation of the name.

Let's say i have the following enum:

public enum Status {
DRAFT, PENDING, COMPLETE;
}
println ("Status=" + Status.DRAFT);


i'd like to get the following:

Status=draft


[Note]: I want to use the enum constants in uppercase, and when requesting the value get the lowercase representation.

Answer

I am replying this question myself as i found the solution interesting and could not find a reply in the site. Just in case somebody else looks for a way to solve this.

The solution is simple, just overwrite the Enum toString method like this:

public enum Status {
    DRAFT, PENDING, COMPLETE;
    public String toString() {
        return name().toLowerCase();
    }
}
println ("Status=" + Status.DRAFT);

This would output the name in lower case.