Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 513
spacebiker Avatar asked Nov 10 '13 19:11

spacebiker


People also ask

How do you make an enum lowercase in Java?

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.

Should enum be uppercase or lowercase?

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.

Can enum be in small case?

OK, no problem.

What is the default value of enum constant?

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).


1 Answers

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.

like image 56
spacebiker Avatar answered Oct 02 '22 23:10

spacebiker