枚举enum在switch中的用法

实际开发中,很多人可能很少用枚举类型。
更多的可能使用常量的方式代替。但枚举比起常量来说,含义更清晰,更容易理解,结构上也更加紧密。

/**
 *枚举类
 */
public enum DemoCode {
	SUCCESS(10000, "操作成功"), 
	FAIL(10001, "操作失败"), 
  
	private int code;
	private String msg;
 
	//为了更好的返回代号和说明,必须重写构造方法
	private Code(int code, String msg) {
		this.code = code;
		this.msg = msg;
	}
 
	public int getCode() {
		return code;
	}
 
	public void setCode(int code) {
		this.code = code;
	}
 
	public String getMsg() {
		return msg;
	}
 
	public void setMsg(String msg) {
		this.msg = msg;
	}
 
	// 根据value返回枚举类型,主要在switch中使用
    public static Code getByValue(int value) {
        for (Code code : values()) {
            if (code.getCode() == value) {
                return code;
            }
        }
        return null;
    }
}

使用:

//获取代码
int code=DemoCode.SUCCESS.getCode();
//获取代码对应的信息
String msg=DemoCode.SUCCESS.getMsg();
 
//在switch中使用通常需要先获取枚举类型才判断,因为case中是常量或者int、byte、short、char,写其他代码编译是不通过的
switch (DemoCode.getByValue(code)) {
	case SUCCESS:
		//......
	break;
 
	case FAIL:
		//......
	break;
}

猜你喜欢

转载自blog.csdn.net/Xxacker/article/details/85225013