I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?
I can get the int values of the statuses but would like the option of getting the string values from the ints as well.
public enum Status { PAUSE(0), START(1), STOP(2); private final int value; private Status(int value) { this.value = value } public int getValue() { return value; } }
Java provides a valueOf(String) method for all enum types. Thus, we can always get an enum value based on the declared name: assertSame(Element.LI, Element. valueOf("LI"));
Enum to String Conversion Example in JavaThere are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
Then you can just do: values. contains("your string") which returns true or false.
if status
is of type Status
enum, status.name()
will give you its defined name.
You can use values()
method:
For instance Status.values()[0]
will return PAUSE in your case, if you print it, toString()
will be called and "PAUSE" will be printed.
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