java 枚举enum的使用(与在switch中的使用)

来源:互联网 发布:软件架构怎么设计 编辑:程序博客网 时间:2024/05/16 03:45


实际开发中,很多人可能很少用枚举类型。更多的可能使用常量的方式代替。但枚举比起常量来说,含义更清晰,更容易理解,结构上也更加紧密。看其他人的博文都很详细,长篇大论的,这里理论的东西不说了,一起看看在实际开发中比较常见的用法,简单明了。



看看枚举类


/** * 操作码类 * @author kokJuis * @version 1.0 * @date 2017-3-6 */public enum Code {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=Code.SUCCESS.getCode();//获取代码对应的信息String msg=Code.SUCCESS.getMsg();//在switch中使用通常需要先获取枚举类型才判断,因为case中是常量或者int、byte、short、char,写其他代码编译是不通过的int code=Code.SUCCESS.getCode();switch (Code.getByValue(code)) {case SUCCESS://......break;case FAIL://......break;}