Java:枚举的通用方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16406298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java: Generic method for Enums
提问by Alexander Mills
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
采纳答案by Mike Samuel
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.
- 它接受枚举的实例,而不是代表您的问题建议您要使用的枚举的类。
- 未使用类型参数。
- 它返回输入而不是实例名称。也许返回实例会更有用——不区分大小写的
Enum.valueOf(String)
. - 它在实例上调用静态方法,以便您可以进行迭代。
EnumSet
为你做所有反射性的东西。