Java: Automatically get Enum from String


The following code will create a static map that contains entries where the key would be the string representation of the enum enum.toString() and value would be the enum itself. This way you can retrieve an enum from its string representation using the static fromString() method.

public enum Type {

    ACCOUNT,
    CLIENT;

    public static Type fromString(final String name) {

        final Type element = sMap.get(name);
        if (element != null) {

            return element;
        }
        throw new IllegalArgumentException(String.format("Unknown value: <%s> for %s", name, Type.class.toString()));
    }

    private static final Map<String, Type> sMap = new HashMap<>();

    static {
        for (final Type t : Type.values()) {

            sMap.put(t.toString(), t);
        }
    }
}

For a more general solution, please checkout http://bytefreaks.net/programming-2/java/java-create-a-lookup-table-for-an-enum, that post will show you how to create a lookup table for any type of value (in contrast to using the enum.toString() method)

Leave a Reply