Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic method to turn an `enum constant name` back into an `enum constant`

Tags:

java

generics

How would the following method that happens to be named reverse be rewritten as a generic method that allows any enumerated type.

public class TestX {

    enum Gender { male, female }

    public static void main(String[] args) {
        System.out.printf("%s\n", TestX.reverse("male").name());
        System.out.printf("%s\n", TestX.reverse("female").name());
    }

    static Gender reverse(String name) {
        for (Gender g: Gender.class.getEnumConstants())
            if (g.name().equals(name))
                return g;
        return null;
    }
}

What I tried (but does not compile at T.class):

<T extends Enum<?>> T reverse2(String name) {
     for (T t: T.class.getEnumConstants())
         if (t.name().equals(name)) return t; 
     return null; 
}
like image 945
H2ONaCl Avatar asked Feb 15 '23 14:02

H2ONaCl


2 Answers

How about

// Every enum class extends Enum<ThisEnumClassName>. 
// Since we want T to be enum we must write it as "extends Enum"
// but Enum is also generic and require type of store parameters 
// so we need to describe it as Enum<T> which finally gives us - T extends Enum<T>
static <T extends Enum<T>> T reverse(String name, Class<T> clazz) {
    for (T t : clazz.getEnumConstants())
        if (t.name().equals(name))
            return t;
    return null;
}

If you want to make it generic you need specify from which Enum you want to get your values. Otherwise there is no way to find correct enym (unless you also put it somewhere in name like full.package.name.of.YourEnum.VALUE).


You can also consider using

Enum.valueOf(YourEnumClass.clazz, "ENUM_FIELD_NAME")

but this approach instead of returning null when enum will not have specified element will throw java.lang.IllegalArgumentException.

like image 143
Pshemo Avatar answered Mar 01 '23 22:03

Pshemo


I believe that the following would work:

static <T extends Enum<T>> T reverse(String name, Class<T> t_class) {
    for (T t: t_class.getEnumConstants())
           if (t.name().equals(name))
                 return t;

    return null;
}
like image 31
Steve P. Avatar answered Mar 01 '23 22:03

Steve P.