我有以下处理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;
}
}
我了解到,所有不具有“ E”值的内容都应设置为EligibilityTypeEnum.INELIGIBLE
。
这就是我的称呼方式:
...
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());
...
}
现在,如果workouts.get(i).getRecommendation()
返回“ C”,则代码将爆炸。
除了try-catch
以外,还有其他人能实现这一目标吗?
是否可以在枚举中设置默认值?
答案 0 :(得分:3)
您可以在EligibilityType
中拥有包含所有可能值的地图
public static final Map<String, EligibilityType> ALL_MAP = Arrays.stream(values())
.collect(Collectors.toMap(Enum::toString, Function.identity()));
那么您就可以优雅地处理默认情况了
EligibilityType.ALL_MAP.getOrDefault(someString, EligibilityType.DEFAULT)