java中的枚举使用
枚举类定义如下: package java1996;
public enum Status {
SCUUESS("1", "success"), FAILED("2", "failed");
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 java1996;
public class StatusTest {
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());
}
}
再比如,我们在操作数据库的时候,通常使用数字保存到数据库中,但是在界面上显示的时候,需要展示其中文意思,那么我们就可以通过下边的方式:
package java1996;
public enum FlightType {
OW(1, "单程"), RT(2, "往返");
public Integer code;
public String 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;
}
FlightType(Integer code, String desc) {
this.code = code;
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;
}
}

浙公网安备 33010602011771号