首页 > 编程语言 > 详细

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

时间:2015-10-16 17:08:34      阅读:207      评论:0      收藏:0      [点我收藏+]

枚举类定义如下:

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

技术分享

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

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方法获得其对应的中文。

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

原文:http://blog.csdn.net/xlgen157387/article/details/46915727

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!