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 {


    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, that post will show you how to create a lookup table for any type of value (in contrast to using the enum.toString() method)

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.