BnJ
BnJ

Reputation: 1044

Best way to find enum from value for many enums

I have a lot of enum.

I would like to add a generic method for all enums allowing to find the enum by the value. Just with something like that :

public static T getEnumFromVal(String val) {
    for (T e : values()) {
        if (e.getVal().equals(val)) {
            return e;
        }
    }
    return null;
}

I could make the enum implements an interface, but unfortunately I am using Java 6 and I can not declare a static method :( ...

Do you have an other idea ?

Upvotes: 0

Views: 202

Answers (2)

mdnghtblue
mdnghtblue

Reputation: 1117

This method already exists in the Java API:

Enum.valueOf(Type.class, "Enum String");

This method also exists on all enum types, for example if you have an Enum called Color:

Color.valueOf("RED");

will return the enum type Color.RED.

Java 6 Enum doc

Upvotes: 8

JB Nizet
JB Nizet

Reputation: 691755

public static <T extends Enum<T> & HasVal> getEnumFromVal(Class<T> enumClass, String val) {
    for (T e : enumClass.getEnumConstants()) {
        if (e.getVal().equals(val)) {
            return e;
        }
    }
    return null;
}

where HasVal is the common interface defining the getVal() method

Upvotes: 2

Related Questions