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

枚举类定义如下:

public enum Status {

    SUCCESS("1","成功"),FAILED("2","失败");

    private String value;
    private String desc;

    private Status(String value, String desc) {
        this.value = value;
        this.desc = 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;
    }
}

使用的方式如下:

public class StatusTest {

    public static void main(String [] args){
        System.out.println(Status.SUCCESS.getValue());
        System.out.println(Status.SUCCESS.getDesc());
        System.out.println(Status.FAILED.getValue());
        System.out.println(Status.FAILED.getDesc());
    }
}

删除结果:

 1
成功
2
失败

再比如,我们在操作数据库的时候,通常使用数字保存到数据库中,但是在界面上显示的时候,需要展示其中文意思
那么我们就可以通过下边的方式:

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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24047659/article/details/86615120