[英]Use ENUM to default value to ineligible
I have following code that handles EligibilityType
: 我有以下代码处理EligibilityType
:
public enum EligibilityType {
E (EligibilityTypeEnum.ELIGIBLE),
I (EligibilityTypeEnum.INELIGIBLE);
private final EligibilityTypeEnum eligibilityTypeEnum;
private EligibilityType(EligibilityTypeEnum eligibilityTypeEnum) {
this.eligibilityTypeEnum = eligibilityTypeEnum;
}
public EligibilityTypeEnum toEligibilityTypeEnum() {
return eligibilityTypeEnum;
}
}
I learned that everything that is not of value "E" should be set to EligibilityTypeEnum.INELIGIBLE
. 我了解到,所有不具有“ E”值的内容都应设置为EligibilityTypeEnum.INELIGIBLE
。
And this is how I am calling it: 这就是我所说的:
...
List<Workout> workouts = workoutResults.getWorkout();
for(int i = 0; i< workouts.size(); ++i) {
...
stin.getWorkouts().get(i).setEligibilityType(EligibilityType.valueOf(workouts.get(i).getRecommendation()).toEligibilityTypeEnum());
...
}
Right now the code blows up if workouts.get(i).getRecommendation()
returns "C". 现在,如果workouts.get(i).getRecommendation()
返回“ C”,该代码将workouts.get(i).getRecommendation()
。
Does anyone see any other way of achieving this except try-catch
? 除了try-catch
之外,还有人看到其他实现此目的的方法吗?
Is there a way to set a default value in enum? 有没有办法在枚举中设置默认值?
you can have in EligibilityType
a map with all possible values 您可以在EligibilityType
拥有包含所有可能值的地图
public static final Map<String, EligibilityType> ALL_MAP = Arrays.stream(values())
.collect(Collectors.toMap(Enum::toString, Function.identity()));
then you can handle gracefully the default case 那么您就可以优雅地处理默认情况
EligibilityType.ALL_MAP.getOrDefault(someString, EligibilityType.DEFAULT)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.