Java Enum with values
I wanted to be able to parse Java enums from a JSON file by not only referring to the numerical value of the enum and also the text in the JSON file should not be all uppercase. I wanted to be able to choose a different display value from the inner value in the Java code. So I came up with this code:
/**
* This is an enum which has an inner value for each
* enumeration value. This allows parsing not only from
* numerical values but also by their inner name.
*/
public enum MySampleEnum {
STARTING("starting"),
RUNNING("running");
STOPPING("stopping");
/**
* Inner value of the enumeration.
*/
private String text;
/**
* Private constructor.
* @param text Inner value of the enumeration.
*/
private JobRunTypeEnum(String text) {
this.text = text;
}
/**
* Returns the string representation of the current enumeration.
* @return Value of the enumeration.
*/
@Override
public String toString() {
return text;
}
/**
* Gets the right enumeration value from a given String, if it exists.
* @param text The String to search for.
* @return Enum value if found, null otherwise.
*/
public static MySampleEnum fromString(String text) {
if (text != null) {
for (MySampleEnum val : MySampleEnum.values()) {
if (text.equalsIgnoreCase(val.text)) {
return val;
}
}
}
return null;
}
}
String
with the inner value. Also there needs to be a private
field to hold the value. The toString()
method should return the inner value and is therefore overridden.
The best thing about this approach is in my eyes, that I am now able to parse the enum from any String
just by calling MySampleEnum.fromString("running")
. This allows me to integrate this in my JSON-parser and create more meaningful JSON objects.