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.
But when you serialize those enum values, you want to use lowercase values of "left", "top", "right", and "bottom". No problem—you can override Side. toString() to return a lowercase version of the enum name.
Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.
OK, no problem.
The default for one who holds a reference to an enum without setting a value would be null (either automatically in case of a class field, or set by the user explicitly).
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 override the Enum toString method like this:
public enum Status { DRAFT, PENDING, COMPLETE; @Override public String toString() { return name().toLowerCase(); } } println ("Status=" + Status.DRAFT);
This would output the name in lower case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With