在 Java 中从枚举获取字符串值

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

我可以得到状态的 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;
}
}
274908 次浏览

if status is of type Status enum, status.name() will give you its defined name.

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.

You can add this method to your Status enum:

 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
}

Use default method name() as given bellows

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());
}
}

I believe enum have a .name() in its API, pretty simple to use like this example:

private int security;
public String security(){ return Security.values()[security].name(); }
public void setSecurity(int security){ this.security = security; }


private enum Security {
low,
high
}

With this you can simply call

yourObject.security()

and it returns high/low as String, in this example

You can use custom values() method:

public enum SortType { Scored, Lasted;

     public int value(){
return this == Lasted ? 1:0;
}
}