我有以下处理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以外,还有人看到其他实现此目的的方法吗?

有没有办法在枚举中设置默认值?

最佳答案

您可以在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)

09-10 19:21