Java中枚举类型Enum的一种使用方式

来源:互联网 时间:1970-01-01

枚举类定义如下:

package com.qunar.enumtest;public enum Status { SCUUESS(1, 成功), FAILED(2, 失败); private String value; private String desc; public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } private Status(String value, String desc) { this.value = value; this.desc = desc; }}

使用的方式如下:

package com.qunar.enumtest;public class StutusTest { public static void main(String[] args) { System.out.println(Status.SCUUESS.getValue()); System.out.println(Status.SCUUESS.getDesc()); System.out.println(Status.FAILED.getValue()); System.out.println(Status.FAILED.getDesc()); }}

vcr9vt2/4tbQo6y1q8rH1Nq958Pmyc/P1Mq+tcTKsbryo6zQ6NKq1bnKvsbk1tDOxNLiy7yjrMTPzt7O0sPHvs2/ydLUzai5/c/Csd+1xLe9yr2jujwvcD4NCjxwcmUgY2xhc3M9"brush:java;">public enum FlightType { OW(1, 单程), RT(2, 往返); public Integer code; public String desc; FlightType(Integer code, String desc) { this.code = code; this.desc = desc; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static FlightType getTypeByCode(Integer code) { FlightType defaultType = FlightType.OW; for (FlightType ftype : FlightType.values()) { if (ftype.code == code) { return ftype; } } return defaultType; } public static String getDescByCode(Integer code) { return getTypeByCode(code).desc; }}

这样的话,我们就可以通过getDescByCode方法获得其对应的中文。

 

相关阅读:
Top