Java: Generic method for Enums

public static <E extends Enum<E>>
String getEnumString(Class<E> clazz, String s){
  for(E en : EnumSet.allOf(clazz)){
    if(en.name().equalsIgnoreCase(s)){
      return en.name();
    }
  }
  return null;
}

The original has a few problems:

  1. It accepts an instance of the enum instead of the class representing the enum
    which your question suggests you want to use.
  2. The type parameter isn’t used.
  3. It returns the input instead of the instance name. Maybe returning the instance would be more useful — a case-insensitive version of Enum.valueOf(String).
  4. It calls a static method on an instance so you can iterate. EnumSet does all the reflective stuff for you.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)