Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic Enum.valueOf method : Enum class in parameter and return Enum item

Tags:

java

enums

I'd like to make a method that implement valueOf on any Enum class passed in parameter (and also wrap some specialized error/missing-name code). So basically, I have several Enum such as:

enum Enum1{ A, B, C }
enum Enum2{ D, E, F }

And I want a method that wrap around valueOf. I could not find a way to directly pass an Enum class in parameter on which I could call valueOf. Here is what I came up with:

private static Enum getEnum(Class<Enum> E, String name){
    for(Enum e: E.getEnumConstants())
        if(e.name().equals(name)){
            return e;
        }
    return null;
}

Which I want to call with: getEnum(Enum1,"A"). But it does not like it:

java: cannot find symbol
  symbol:   variable Enum1
  location: class Main
like image 383
Juh_ Avatar asked Feb 11 '26 14:02

Juh_


1 Answers

Why implement your own, when you can use Java's own implementation for this?

 YourEnum yourEnum = Enum.valueOf(YourEnum.class, value);

http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)

Your method then becomes:

private static <E extends Enum<E>> E getEnum(Class<E> enumClass, String name){
    try {
        return Enum.valueOf(enumClass, name);
    } catch(IllegalArgumentException e) {
        return null;
    }
}

and you can call it with:

getEnum(Enum1.class, "A")
like image 118
EpicPandaForce Avatar answered Feb 13 '26 10:02

EpicPandaForce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!