我有一些看起来像这样的C++代码:
enum {
FOO = 0x01,
BAR = 0x09;
};
switch (baz) {
case FOO:
{
//...
}
break;
case BAR:
{
//...
}
break;
}
是否可以在Java中复制此行为?
最佳答案
是的,Java有枚举:
public enum BazEnum {
FOO(0x01),
BAR(0x09);
private int value;
BazEnum(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static BazEnum fromValue(int value) {
for (BazEnum curenum : BazEnum.values()) {
if (curenum.getValue() == value) {
return curenum;
}
}
return null;
}
}
public class MainClass {
public static void main(String[] params) {
BazEnum baz = BazEnum.fromValue(0x09);
switch baz {
case FOO:
...
break;
case BAR:
...
break;
default:
...
break;
}
}
}