Reputation: 100010
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
Upvotes: 32
Views: 30366
Reputation: 120516
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:
Enum.valueOf(String)
.EnumSet
does all the reflective stuff for you.Upvotes: 71