记一次使用switch时使用枚举类型导致constant expression required

枚举类如下

/**
 * 保证金操作原因类型
 */
public  enum ReasonEnum {
    REASON1(1,"保证金-缴存"),
    REASON2(2,"保证金-解冻"),
    REASON3(3,"保证金-解冻(退款锁定)"),
    REASON4(4,"保证金-缴存(退款锁定)"),
    REASON5(5,"保证金-解冻(维权锁定)"),
    REASON6(6,"保证金-缴存(维权锁定)"),
    REASON7(7,"保证金-扣除补缴"),
    REASON8(8,"保证金-不可支配额度释放"),
    REASON9(9,"保证金-不可支配额度锁定"),
    REASON10(10,"保证金-扣除转移"),
    REASON11(11,"交易退款-保证金退款"),
    REASON12(12,"其他支出-交易赔付(保证金扣款)"),
    REASON13(13,"其他支出-违规违约金(保证金扣款)"),;

    private int code;
    private String reason;

    ReasonEnum(int code, String reason) {
        this.code = code;
        this.reason = reason;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }
    public static ReasonEnum getByValue(int code) {
        for (ReasonEnum codes : values()) {
            if (codes.getCode() == code) {
                return codes;
            }
        }
        return null;
    }


}

直接使用
switch(typeId){
case ReasonEnum.REASON1.getCode():
}
时报错constant expression required
解决
在枚举类中添加了getByValue()方法

 public Integer frozenGuaranteeMoney(TbGuaranteeRecordDto tbGuaranteeRecord, Long userId) {
       int typeId = tbGuaranteeRecord.getTypeId();
        Integer stauts = 0;
        switch (ReasonEnum.getByValue(typeId)) {
            case REASON1: {
                stauts = hanlerGuarantee(tbGuaranteeRecord, userId);
                break;
            }
            
            default:{
                throw new RrkException("操作失败");
            }

        }
        return stauts;

    }

发布了26 篇原创文章 · 获赞 1 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42643690/article/details/102244267
今日推荐