Java Enums with String values
April 10, 2018
I wanted to create an enum
in Java 8 which was a set list of strings that can limit the values an attribute can hold. This can be done with:
public enum Systems { REGISTER("register"), PRINT("print"), MANAGEMENT("management"), ; private final String name; private Systems(String name) { this.name = name; } @Override public String toString() { return this.name; } public static Systems fromString(String text) { for (Systems ts : Systems.values()) { if (ts.toString().equals(text)) { return ts; } } throw new IllegalArgumentException("No constant with text " + text + " found"); } }
The enum can be used as a type, and the string values can be obtained using toString()
. To convert a string to the appropriate enum value, use fromString()
:
Systems value = Systems.REGISTER; assertEqual(value.toString(), "register"); Systems valueFromString = Systems.fromString("print"); assertEqual(Systems.PRINT, valueFromString);
Xml and JAXB
If you want to use the enums as above with JAXB, the upper case (constant) value will be used by default. To use the string value instead you need to create an adapter and attach it to the enum.
public class SystemsAdapter extends XmlAdapter<String,Systems> { public String marshal(Systems system) { return system.toString(); } public Systems unmarshal(String val) { return Systems.fromString(val); } }
Then, where the enum is used, add an annotation:
@XmlJavaTypeAdapter(SystemsAdapter.class) private Systems system;