java 枚举使用方法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_39150374/article/details/102585052

前言

在项目中有很多常量,我们都是使用枚举(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; //  不同的业务有不同的处理方式
      }
}

猜你喜欢

转载自blog.csdn.net/qq_39150374/article/details/102585052