How do I replicate this C++ enum switch in Java?
I have some C++ code that looks like this:
enum {
FOO = 0x01,
开发者_如何学编程 BAR = 0x09;
};
switch (baz) {
case FOO:
{
//...
}
break;
case BAR:
{
//...
}
break;
}
Is it possible to replicate this behaviour in Java?
Yes, Java has enums:
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;
}
}
}
Take a look at the Java Tutorial on Enum Types which has examples on constructing enums and using them in switch statements.
Sure, just give the enum a name:
enum Baz
{
FOO, BAR;
}
And then you can switch over expressions of type Baz
:
switch (baz)
{
case FOO:
{
}
break;
case BAR:
{
}
break;
}
You can still associate FOO
and BAR
with the values 1 and 9 if you want to:
enum Baz
{
FOO(0x01), BAR(0x09);
Baz(int value)
{
this.value = value;
}
public final int value;
}
Then you can say baz.value
to get the associated value.
public enum Enum{
FOO(0x01),
BAR(0x09);
Enum(int value){
this.value=value;
}
private int value;
};
public void test() {
Enum testEnum = null;
switch(testEnum){
case FOO:{}break;
case BAR:{}break;
}
}
While Java has enum's they are objects not primitives. It may be simpler to just use constants
static final int
FOO = 0x01,
BAR = 0x09;
switch (baz) {
case FOO:
//...
break;
case BAR:
//...
break;
}
just create an enum xDD
public enum EnumName { Foo(),Bar(); } switch (baz) { case : EnumName.Foo code break; }
精彩评论