这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。
下面是我的代码问题示例:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
这是我的问题-我正在寻找(如果它甚至存在)等价于ArrayList.contains();的enum。
下面是我的代码问题示例:
enum choices {a1, a2, b1, b2};
if(choices.???(a1)}{
//do this
}
现在,我意识到字符串的数组列表在这里是更好的路由,但我必须通过其他地方的开关/case运行我的enum内容。这就是我的问题所在。
假设这样的东西不存在,我该怎么做呢?
当前回答
我为这个验证创建了下一个类
public class EnumUtils {
public static boolean isPresent(Enum enumArray[], String name) {
for (Enum element: enumArray ) {
if(element.toString().equals(name))
return true;
}
return false;
}
}
用法示例:
public ArrivalEnum findArrivalEnum(String name) {
if (!EnumUtils.isPresent(ArrivalEnum.values(), name))
throw new EnumConstantNotPresentException(ArrivalEnum.class,"Arrival value must be 'FROM_AIRPORT' or 'TO_AIRPORT' ");
return ArrivalEnum.valueOf(name);
}
其他回答
解决方案,检查值是否存在,以及获得enum值返回:
protected TradeType getEnumType(String tradeType) {
if (tradeType != null) {
if (EnumUtils.isValidEnum(TradeType.class, tradeType)) {
return TradeType.valueOf(tradeType);
}
}
return null;
}
虽然迭代一个列表或捕捉一个异常对于大多数情况来说已经足够好了,但我正在寻找一些可重用的东西,这些东西对于大型枚举来说也很好。最后,我写下了这样一段话:
public class EnumValidator {
private final Set<String> values;
private EnumValidator(Set<String> values) {
this.values = values;
}
public static <T extends Enum<T>> EnumValidator of(Class<T> enumType){
return new EnumValidator(Stream.of(enumType.getEnumConstants()).map(Enum::name).collect(Collectors.toSet()));
}
public boolean isPresent(String et){
return values.contains(et);
}
}
我会写,
Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");
Enum#equals只适用于对象比较。
请使用Apache commons lang3库
EnumUtils.isValidEnum(MyEnum.class, myValue)
com.google.common.collect.Sets.newHashSet(MyEnum.values()).contains("myValue")