Home > Java > javaTutorial > How to use java enumerations

How to use java enumerations

(*-*)浩
Release: 2019-10-18 16:04:30
forward
2573 people have browsed it

Preface

How to use java enumerations

There are many constants in the project, we all use enumerations (enum) to deal with them. Now I will share with you a more common code

Enumeration

/**
* 描述: 常量类型
* /
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("");
    }
}
Copy after login

Enumeration is relatively simple to use in java code

In How to use the application layer

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

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

The above is the detailed content of How to use java enumerations. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template