假设我有一个如下所示的枚举结构
public enum MyItems {
pc("macbook"),
phone("nokia"),
food("sandwich"),
animal("dog");
private String item;
MyStuff(String stf) {
item = stf;
}
public String identify() {
return item;
}
}
现在,假设我想知道我拥有的元素是什么“类型”。例如,对于“macbook”,这将产生 pc。同样,“三明治”代表一种食品。
我有以下 for 循环来检查字符串是否属于枚举:
String currentItem; //Some arbitrary string, such as "macbook"/"nokia", etc.
for(MyStuff stuff : MyStuff.values()) {
if(stuff.identify().equals(currentItem)) {
//PRINT OUT:
//currentItem + " is a " + pc/phone/food/animal
}
}
也就是说,我如何从获取枚举值的参数到它代表的枚举值“类型”。
这是所需的输出:
currentItem = "nokia"
>>>> nokia is a [phone]
最佳答案
您可以将 revese 查找方法添加到您的枚举中:
public enum MyItems {
...
public static MyItems resolve(String name) {
for (MyItems item : values()) {
if (item.identify().equals(name)) {
return item;
}
}
return null;
}
}
用法:
String currentItem = "nokia";
MyItems item = MyItems.resolve(currentItem);
System.out.println(currentItem + " is a [" + item + "]");
关于java - 从其参数获取 ENUM 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32593339/