[Java] Constant expression required

在switch-case语句中,case后提示“Constant expression required” – 需要常量表达式。

GradeEnum.java

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;

/**
 * @author lizh
 * @date 2020/6/29
 */
@Data
@AllArgsConstructor
@Getter
public enum GradeEnum {
     
    GRADE_ONE(1, "小学一年级"),
    GRADE_TWO(2, "小学二年级"),
    GRADE_THREE(3, "小学三年级"),
    GRADE_FOUR(4, "小学四年级"),
    ;

    private Integer code;
    private String desc;
}

SwitchCaseTest.java

/**
 * @author lizh
 * @date 2020/6/29
 */
public class SwitchCaseTest {
     
    public void deal(Integer grade) {
     
        switch (grade) {
     
            case GradeEnum.GRADE_ONE.getCode(): // 这里提示:Constant expression required
                // do something
                break;
            default:
                // do something
                break;
        }
    }
}

对于case语句,在编译期间就要确定值,这里GradeEnum.GRADE_ONE.getCode() 在运行期才能确定值。

修改方案:case 后使用枚举常量。
在枚举类中增加方法:

public enum GradeEnum {
     
    // 忽略部分代码

    public static GradeEnum getGradeEnumByCode(Integer code) {
     
        for (GradeEnum gradeEnum : GradeEnum.values()) {
     
            if (gradeEnum.getCode().equals(code)) {
     
                return gradeEnum;
            }
        }
        return null;
    }
}

switch-case语句修改为:

    public void deal(Integer grade) {
     
        GradeEnum gradeEnum = GradeEnum.getGradeEnumByCode(grade);
        if (gradeEnum == null) {
     
            // do something
        } else {
     
            switch (gradeEnum) {
     
                case GRADE_ONE:
                    // do something
                    break;
                default:
                    // do something
                    break;
            }
        }
    }

你可能感兴趣的:(JAVA,java)