Preskočiť na hlavný obsah

Get Enum constant of an Enum by String

Method cast(Class, String) builds the enum value constant of the specified Enum. The name must match exactly (case) an identifier used to declare an enum constant in the given Enum.

@SuppressWarnings({ "rawtypes", "unchecked" })
public static <E extends Enum<E>> E cast(String name, Class&lt;E> clazz) {

  if (clazz == null || name == null || name.isEmpty()) {
    return null;
  }

  try {
   return (E) Enum.valueOf((Class<Enum>) clazz, name);
  } catch (Throwable e) {
    throw new RuntimeException("Enum cast error: '" + name
 + "' in not valid value of '" + clazz.getName() + "'");
  }
}