我有一个这样定义的枚举,我希望能够获得各个状态的字符串.我该怎么写这样的方法?
我可以获取状态的int值,但是也希望从int中获取字符串值.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
har*_*rsh 99
如果status
是Status
enum 类型,status.name()
将为您提供其定义的名称.
Bis*_*kar 11
使用默认方法名称()作为给定的波纹管
public enum Category {
ONE("one"),
TWO ("two"),
THREE("three");
private final String name;
Category(String s) {
name = s;
}
}
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(Category.ONE.name());
}
}
Run Code Online (Sandbox Code Playgroud)
您可以将此方法添加到Status枚举:
public static String getStringValueFromInt(int i) {
for (Status status : Status.values()) {
if (status.getValue() == i) {
return status.toString();
}
}
// throw an IllegalArgumentException or return null
throw new IllegalArgumentException("the given number doesn't match any Status.");
}
public static void main(String[] args) {
System.out.println(Status.getStringValueFromInt(1)); // OUTPUT: START
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
207477 次 |
最近记录: |