问题
I'd like to make a method that implement valueOf
on any Enum class passed in parameter (and also wrap some specialized error/missing-name code).
So basically, I have several Enum such as:
enum Enum1{ A, B, C }
enum Enum2{ D, E, F }
And I want a method that wrap around valueOf
. I could not find a way to directly pass an Enum class in parameter on which I could call valueOf
. Here is what I came up with:
private static Enum getEnum(Class<Enum> E, String name){
for(Enum e: E.getEnumConstants())
if(e.name().equals(name)){
return e;
}
return null;
}
Which I want to call with: getEnum(Enum1,"A")
. But it does not like it:
java: cannot find symbol
symbol: variable Enum1
location: class Main
回答1:
Why implement your own, when you can use Java's own implementation for this?
YourEnum yourEnum = Enum.valueOf(YourEnum.class, value);
http://docs.oracle.com/javase/7/docs/api/java/lang/Enum.html#valueOf(java.lang.Class,%20java.lang.String)
Your method then becomes:
private static <E extends Enum<E>> E getEnum(Class<E> enumClass, String name){
try {
return Enum.valueOf(enumClass, name);
} catch(IllegalArgumentException e) {
return null;
}
}
and you can call it with:
getEnum(Enum1.class, "A")
回答2:
For pass classes you should use class
getEnum(Enum1.class,"A")
And then update method signature to
private static Enum getEnum(Class<? extends Enum> E, String name){
...
}
来源:https://stackoverflow.com/questions/26357132/generic-enum-valueof-method-enum-class-in-parameter-and-return-enum-item