在使用枚举之前检查有效的枚举值 [英] Check valid enum values before using enum
问题描述
public enum Fruit {
APPLE(apple),
ORANGE( 橙色);
;
private final String fruitname;
水果(String fruitname){
this.fruitname = fruitname;
}
public String fruitname(){return fruitname;}
}
我想检查一下,在尝试使用相关枚举之前,是否说香蕉是我的枚举值之一。我可以通过将我的字符串与
Compare.values()[i] .fruitname
但我想要像(pseduo-code)这样做:
if(Fruit.values()。contains(myStringHere)){...
可以吗?我应该完全使用别的吗(Arrays?Maps?)?
编辑:最后我和NawaMan的建议一起走了,但感谢大家所有的帮助输入。
我真的不知道一个内置的解决方案。所以你可能需要自己写一个静态方法。
public enum Fruit {
...
static public boolean isMember(String aName){
Fruit [] aFruits = Fruit.values();
(水果aFruit:aFruits)
if(aFruit.fruitname.equals(aName))
返回true;
返回false;
}
...
}
I'm trying to lookup against an Enum set, knowing that there will often be a non-match which throws an exception: I would like to check the value exists before performing the lookup to avoid the exceptions. My enum looks something like this:
public enum Fruit {
APPLE("apple"),
ORANGE("orange");
;
private final String fruitname;
Fruit(String fruitname) {
this.fruitname = fruitname;
}
public String fruitname() {return fruitname;}
}
and I want to check if, say, "banana" is one of my enum values before attempting to use the relevant enum. I could iterate through the permissible values comparing my string to
Fruit.values()[i].fruitname
but I'd like to be able to do something like (pseduo-code):
if (Fruit.values().contains(myStringHere)) {...
Is that possible? Should I be using something else entirely (Arrays? Maps?)?
EDIT: in the end I've gone with NawaMan's suggestion, but thanks to everyone for all the helpful input.
I really don't know a built-in solution. So you may have to write it yourself as a static method.
public enum Fruit {
...
static public boolean isMember(String aName) {
Fruit[] aFruits = Fruit.values();
for (Fruit aFruit : aFruits)
if (aFruit.fruitname.equals(aName))
return true;
return false;
}
...
}
这篇关于在使用枚举之前检查有效的枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!