Java中的anenum
是一个类,编译器添加了一个静态valueOf(String name)
方法。因此,如果您有:
enum MyEnum {
ONE(1.0), TWO(2.0), THREE(3.0);
private double myDouble;
MyEnum(double d) {
myDouble = d;
}
public double getDouble() {
return myDouble;
}
}
你可以说:
MyEnum e = MyEnum.valueOf("ONE");
assert(e.equals(MyEnum.ONE));
System.out.println(e.getDouble());
更流行的用于 Java 的 JSON 解析器可以很好地处理枚举。以下是 Gson 的示例:
public class App
{
public static void main(String[] args)
{
// Array containing your enum constants
String json = "[\"ONE\",\"TWO\",\"THREE\"]";
Type t = new TypeToken<Collection<MyEnum>>(){}.getType();
Collection<MyEnum> c = new Gson().fromJson(json, t);
for (MyEnum me : c)
{
System.out.println(me);
switch(me)
{
case ONE:
System.out.println("This is equal to MyEnum.ONE");
break;
case TWO:
System.out.println("This is equal to MyEnum.TWO");
break;
case THREE:
System.out.println("This is equal to MyEnum.THREE");
break;
}
System.out.println(me.getDouble());
}
}
}
输出:
ONE
这等于 MyEnum.ONE
1.0
TWO
这等于 MyEnum.TWO
2.0
三
这等于 MyEnum.THREE
3.0