3

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
1
  • 2
    isn't there a method for that - Enum.valueOf(Enum1.class, value);? Commented Oct 14, 2014 at 9:44

2 Answers 2

9

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")
Sign up to request clarification or add additional context in comments.

2 Comments

that method seems useful, but I still got the problem of the getEnum signature (I want to wrap the valueOf call into it to add some more code around it.
well based on the valueOf signature, public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name), you would need private static <E extends Enum<E>> E getEnum(Class<E> clazz, String name)
4

For pass classes you should use class

getEnum(Enum1.class,"A")

And then update method signature to

private static Enum getEnum(Class<? extends Enum> E, String name){
    ...
}

4 Comments

It does not correspond to the signature of getEnum which takes a class<Enum>. And if I change that for class<?> then E.getEnumConstants returns object...
update method signature to private static Enum getEnum(Class<? extends Enum> E, String name)
alright! And then I can use @Zhuinden Enum.valueOf too :-)
I finally selected Zhuinden answer because it returns the correct Enum type, not just an Enum.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.