我需要比较枚举,但请注意如何访问它们。我得到了一些字符串的直播活动。我需要将它与一组字符串进行比较以执行必要的操作。我试图使用枚举,但它无法正常工作
public enum Type {
TYPE_ONE("event/one");
TYPE_TWO("event/two");
private Type(String mType){
this.mType = mType;
}
private final String mType;
public String getType(){return mType;}
}
我想在Switch / Case中进行比较:
switch (event.getType()){
case Type.TYPE_ONE.getType(): // says "Constant expression required"
Do something:
case Type.TYPE_TWO.getType(): // says "Constant expression required"
Do something;
}
答案 0 :(得分:1)
您希望抽象方法如何?
public enum Type {
TYPE_ONE("event/one"){
@Override
public String getType(){return mType;}
},
TYPE_TWO("event/two"){
@Override
public String getType(){return mType;}
};
private final String mType;
abstract public String getType();
private Type(String mType){
this.mType = mType;
}
}
如果你想像下面这样使用String,我们需要使用JDK 7.当我们使用Java版本时,我们必须选择目标API 19(Kitkat)。
String hoge = "hoge";
switch (hoge) {
case "hoge":
break;
default:
break;
}
所以我建议你做以下几点;
Type type = Type.TYPE_TWO;
switch (type) {
case TYPE_ONE:
break;
case TYPE_TWO:
break;
default:
break;
}
顺便说一下,这个方法可以这样访问;
Type type = Type.TYPE_TWO;
String strType = type.getType();
if (strType.equals("event/two")) {/*do something*/}
答案 1 :(得分:0)
编辑你的枚举
public enum Type {
TYPE_ONE("event/one");
TYPE_TWO("event/two");
private Type(String mType){
this.mType = mType;
}
private final String mType;
public String getType(){return mType;}
//Provide the event type and get back the match Type enum
public Type getTypeFromStringType(String type) {
for (Type t : Type.values()) {
if (type.equals(t.getType()) {
return t;
}
}
return null
}
}
和你的方法
//You have to switch on an enum value
switch (getTypeFromStringType(event.getType())){
case Type.TYPE_ONE;
break;
case Type.TYPE_TWO;
break;
}