在使用枚举之前检查有效的枚举值 [英] Check valid enum values before using enum

查看:98
本文介绍了在使用枚举之前检查有效的枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图查找一个枚举集,知道通常会有一个非匹配引发异常:我想在执行查找之前检查存在的值以避免异常。我的枚举看起来像这样:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆