首頁  >  文章  >  Java  >  java 枚舉使用方法

java 枚舉使用方法

(*-*)浩
(*-*)浩轉載
2019-10-18 16:04:302452瀏覽

前言

java 枚舉使用方法

#在專案中有很多常數,我們都是使用枚舉(enum)來處理,下面我就跟大家分享一個比較通用的程式碼

枚舉

/**
* 描述: 常量类型
* /
public enum ClientType {
    SYSTEM(0, "后台管理"),
    EDUCATION(1, "教育系统"),
    GOVERNMENT(2, "政府系统");

    private Integer value;
    private String text;

    ClientType(Integer value, String text) {
        this.value = value;
        this.text = text;
    }

    public Integer getValue() {
        return this.value;
    }

    public String getText() {
        return this.text;
    }
    
    /**
     *根据值找相对应的中文
    */
    public static String getTextByValue(Integer value) {
        return Arrays.stream(values()) // java8新特性 -- stream流
                .filter(x -> x.getValue().equals(value))
                .map(ClientType::getText)
                .findFirst().orElse("");
    }
}

枚舉在java程式碼使用比較簡單

在應用層的使用方法

// 获取类型相对应的数值
Integer type = ClientType .SYSTEM.getValue();

// 获取中文
Intger code = 1; // 初始化
for (ClientType value : ClientType.values()) {
 if (type.value== code) {
         return type; //  不同的业务有不同的处理方式
      }
}

以上是java 枚舉使用方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除