-1

所有String to Enum转换示例只采用一个字符串,但在我的示例字符串中,像这样......

String allDays="MONDAY,SUNDAY,FRIDAY";

和我的枚举类这样..

public enum WeekdayType {

    MONDAY(Calendar.MONDAY), TUESDAY(Calendar.TUESDAY), WEDNESDAY(
            Calendar.WEDNESDAY), THURSDAY(Calendar.THURSDAY), FRIDAY(
            Calendar.FRIDAY), SATURDAY(Calendar.SATURDAY), SUNDAY(
            Calendar.SUNDAY);

    private int day;

    private WeekdayType(int day) {
        this.day = day;
    }

    public int getDay() {
        return day;
    }
}

所以在那段时间WeedayType.valueOf(allDay)给出了错误.....对此有任何建议..

4

2 回答 2

2

试试这样:

String allDays = "MONDAY,SUNDAY,FRIDAY";
        for (String day : allDays.split(",")) {
            System.out.println(WeekdayType.valueOf(day));
        }
于 2012-12-18T06:04:44.497 回答
1

您将收到以下错误

java.lang.IllegalArgumentException: No enum const class com.java.core.Test$WeekdayType.MONDAY,SUNDAY,FRIDAY

原因是您将以下字符串传递给您的WeedayType枚举,正如异常所说,这是一个非法参数。

String allDays = "MONDAY,SUNDAY,FRIDAY"; 
WeedayType.valueOf(allDay); 

您可以传递给 valueOf 方法的有效值是“MONDAY”、“TUESDAY”等(即您的枚举名称)。其他值会为您提供 java.lang.IllegalArgumentException,这是正确的行为。

于 2012-12-18T06:22:31.293 回答