如何在java中使键值像枚举一样

2022-09-04 23:57:33

我需要制作一个包含一些带有空格及其值的字符串,如下所示:Enumint

public enum status{
Active(1),
Inactive(2);
}

因为我在休眠状态下使用它,并且还会将其转换为羊驼js形式的JSON。

喜欢:

[{"text": "Inactive", "value":"2"},{"text": "Active", "value":"1"}]

我被困在制作.如何制作这种类型的?enumenum


答案 1

不能在字符串之间放置空格。您可以使用下划线代替下划线,如下所示:

In_Active

您可以通过以下方式使用:

enum Status {

    ACTIVE("Active", 1), IN_ACTIVE("In Active", 2);

    private final String key;
    private final Integer value;

    Status(String key, Integer value) {
        this.key = key;
        this.value = value;
    }

    public String getKey() {
        return key;
    }
    public Integer getValue() {
        return value;
    }
}

答案 2

您可以将多个值保存在一个中,甚至可以让 getter 来处理它们。以下是我曾经使用过的一个示例(我尝试将其适应您的问题):enum

public enum Status{

    ACTIVE(1, "Active"),
    INACTIVE(2, "In Active");

    private final Integer value;
    private final String text;

    /**
     * A mapping between the integer code and its corresponding text to facilitate lookup by code.
     */
    private static Map<Integer, Status> valueToTextMapping;

    private Status(Integer value, String text){
        this.value = value;
        this.text = text;
    }

    public static Status getStatus(Integer i){
        if(valueToTextMapping == null){
            initMapping();
        }
        return valueToTextMapping.get(i);
    }

    private static void initMapping(){
        valueToTextMapping = new HashMap<>();
        for(Status s : values()){
            valueToTextMapping.put(s.value, s);
        }
    }

    public Integer getValue(){
        return value;
    }

    public String getText(){
        return text;
    }

    @Override
    public String toString(){
        final StringBuilder sb = new StringBuilder();
        sb.append("Status");
        sb.append("{value=").append(value);
        sb.append(", text='").append(text).append('\'')
        sb.append('}');
        return sb.toString();
    }
}

因此,在您的代码中,您可以简单地使用,它将表示您的Enum的实例,该实例保持不变,并且以您想要的方式存在Status.ACTIVEvaluetext