java 枚举使用方法

(*-*)浩
(*-*)浩 转载
2019-10-18 16:04:30 2005浏览

前言

在项目中有很多常量,我们都是使用枚举(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,如有侵犯,请联系admin@php.cn删除