Friedrich Ewald My Personal Website

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;
	}
}
To achieve this, it is necessary to overwrite the default constructor of the enum and give it a parameter which is a 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.


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.