欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java 如何创建一个好用的枚举类

程序员文章站 2022-06-03 21:17:52
...

话不多说,直接上代码:

public enum MarryStatusEnum {

    /**
     * 单身
     */
    SINGLE("single", "单身"),
    /**
     * 已婚
     */
    MARRIED("married ", "已婚");


    private final String value;

    private final String name;

    private static Map<String, MarryStatusEnum> valueMap = new HashMap<>();

    static {
        Arrays.stream(MarryStatusEnum.values()).forEach(e -> valueMap.put(e.value, e));
    }

    MarryStatusEnum(String value, String name) {
        this.value = value;
        this.name = name;
    }

    public static MarryStatusEnum of(String code) {
        return valueMap.get(code);
    }

    public String valueName() {
        return this.name;
    }

    public String value() {
        return this.value;
    }

    @Override
    public String toString() {
        return "type{" +
                "value='" + value + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}
相关标签: Java java