试图通过其常量参数/字段值(即 value0/value1/value2)找到一个元素而不进行迭代;有办法吗?找到适用于枚举常量名称(即 CONSTANT0/CONSTANT1/CONSTANT2)而不是该名称的参数/字段值的 guava 实用程序方法。
import com.google.common.base.Enums;
enum Enum {
CONSTANT0("value0"), CONSTANT1("value1"), CONSTANT2("value2");
private final String value;
Enum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class Driver {
public static void main(String[] args) {
// prints when input is value0
for (Enum constant : Enum.values()) {
if (constant.getValue().equalsIgnoreCase(args[0])) {
System.out
.println("vanilla version works with value i.e. java Driver value0"
+ args[0]);
}
}
// prints when input is CONSTANT0
if (Enums.getIfPresent(Enum.class, args[0]).isPresent())
System.out
.println("guava version works with constant i.e. java Driver CONSTANT0"
+ args[0]);
}
}