Java: Generic method for Enums
25,302
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:
- It accepts an instance of the enum instead of the class representing the enum which your question suggests you want to use.
- The type parameter isn't used.
- 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)
. - It calls a static method on an instance so you can iterate.
EnumSet
does all the reflective stuff for you.
Author by
Alexander Mills
Dev, Devops, soccer coach. https://www.github.com/oresoftware
Updated on November 22, 2020Comments
-
Alexander Mills over 3 years
Help me understand generics. Say I have two enums as inner classes like so:
public class FoodConstants { public static enum Vegetable { POTATO,BROCCOLI,SQUASH,CARROT; } public static enum Fruit { APPLE,MANGO,BANANA,GUAVA; } }
Instead of having both enums implement an interface, and have to implement the same method twice, I would like to have a method in the outer class that does something like:
public <e> String getEnumString<Enum<?> e, String s) { for(Enum en: e.values()) { if(en.name().equalsIgnoreCase(s)) { return s; } } return null; }
However this method does not compile. What I am trying to do is find out if a string value is the name of an enumerated value, in ANY enum, whether it's Vegetable, Fruit, what not. Regardless of whether this is in fact a redundant method, what is wrong with the one I am trying to (re)write?
Basically I would like to do this:
public class FoodConstants { public static enum Vegetable { POTATO,BROCCOLI,SQUASH,CARROT; } public static enum Fruit { APPLE,MANGO,BANANA,GUAVA; } public <e> String getEnumString<Enum<?> e, String s) { for(Enum en: e.values()) { if(en.name().equalsIgnoreCase(s)) { return s; } } return null; } } //end of code