Enum.valueOf(Class<T> enumType, String name) question

Viewed 27360

I am trying to get around a compile error ("Bound mismatch: ...") relating to dynamic enum lookup.

Basically I want to achieve something like this:

String enumName = whatever.getEnumName();
Class<? extends Enum<?>> enumClass = whatever.getEnumClass();
Enum<?> enumValue = Enum.valueOf(enumClass, enumName);

Whatever I do, I always end up with that compile error. Honestly, generics and enums are quite mindboggling to me...

What am I doing wrong here?

4 Answers

Thx @Sbodd for the answer. I took this example, added the exception we know from the standard anEnum.valueOf("ELVIS") and changed the generic method args in a way that we can use it like this:

       King king = findEnumValue(King.class, "ELVIS");
       System.out.println(String.valueOf(king)); 

Method:

/**
 * Returns the {@link Enum} for the given {@link Enum#name()} String of the given enum type. 
 * <p>
 * Example: 
 * <pre>
 * {@code     
      King king = findEnumValue(King.class, "ELVIS");
      System.out.println(String.valueOf(king));
 * }
 * </pre>
 * @param enumType the class of the enum, e.g. {@code King.class}. 
 * 
 * @param enumName the {@link Enum#name()}, e.g. "ELVIS". 
 * 
 * @return the enum instance or an exception. 
 * 
 * @throws IllegalArgumentException if the given {@code enumName} is no enum constant in the given {@code enumType}. 
 */
public static <T extends Enum<T>> T findEnumValue(Class<T> enumType, String enumName) throws IllegalArgumentException {
    T result = Arrays.stream(enumType.getEnumConstants())
                 .filter(e -> e.name().equals(enumName))
                 .findFirst()
                 .orElse(null);
    if(result == null)
    {
        throw new IllegalArgumentException(
                    "No enum constant " + enumType.getCanonicalName() + "." + enumName);
    }
    else
    {
        return result;
    }
}

public enum King{
    ELVIS
}
Related