从Java中的枚举获取字符串值 [英] Getting String value from enum in Java

查看:669
本文介绍了从Java中的枚举获取字符串值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的枚举,我希望能够获取单个状态的字符串。我应该如何编写这样的方法?



我可以获取状态的int值,但是也希望从int中获取字符串值。 p>

  public enum状态{
PAUSE(0),
START(1),
STOP 2);

private final int value;

私人状态(int value){
this.value = value
}

public int getValue(){
return value;
}
}


解决方案

你可以使用 values()方法:



例如 Status.values()[0 ] 将在您的情况下返回PAUSE,如果您打印, toString()将被调用,并将打印PAUSE。


I have a enum defined like this and I would like to be able to obtain the strings for the individual statuses. How should I write such a method?

I can get the int values of the statuses but would like the option of getting the string values from the ints as well.

public enum Status {
    PAUSE(0),
    START(1),
    STOP(2);

    private final int value;

    private Status(int value) {
        this.value = value
    }

    public int getValue() {
        return value;
    }
}

解决方案

You can use values() method:

For instance Status.values()[0] will return PAUSE in your case, if you print it, toString() will be called and "PAUSE" will be printed.

这篇关于从Java中的枚举获取字符串值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆