java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java枚举通过Code获取相应的Value值

Java枚举通过Code获取相应的Value值实现方式

作者:一恍过去

本文介绍了枚举定义、如何通过code获取value的方法,并提供了一个完整的代码示例,通过实际测试,证明了该方法的有效性,希望本文能够为读者提供参考,并鼓励大家支持脚本之家

1、枚举定义

public enum TestEnum {
    /**
     * 启动状态
     */
    ENABLE(1, "启动"),

    /**
     * 禁用状态
     */
    DIS_ENABLE(2, "禁用");


    private final Integer code;
    private final String value;

    public Integer getCode() {
        return code;
    }

    public String getValue() {
        return value;
    }

    TestEnum(Integer code, String value) {
        this.code = code;
        this.value = value;
    }
}

2、通过code获取value方法

    public static String getValue(Integer code) {
        for (TestEnum value : TestEnum.values()) {
            if (value.getCode().equals(code)) {
                return value.getValue();
            }
        }
        return null;
    }

3、完整代码

public enum TestEnum {
    /**
     * 启动状态
     */
    ENABLE(1, "启动"),

    /**
     * 禁用状态
     */
    DIS_ENABLE(2, "禁用");


    private final Integer code;
    private final String value;

    public Integer getCode() {
        return code;
    }

    public String getValue() {
        return value;
    }

    TestEnum(Integer code, String value) {
        this.code = code;
        this.value = value;
    }

    public static String getValue(Integer code) {
        for (TestEnum value : TestEnum.values()) {
            if (value.getCode().equals(code)) {
                return value.getValue();
            }
        }
        return null;
    }
}

4、测试

public class Test {
    public static void main(String[] args) {
        // 设置一个code值
        Integer code = 1;
        System.out.println("获取枚举的value:" + TestEnum.getValue(code));
    }
}

效果:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文