問題
想使用switch去替換掉if-else,想到Hobby這個類里面的type屬性正好是個枚舉,就想用枚舉去實現,結果發現這樣是有問題的。
枚舉類
public enum HobbyEnum{
SIGN("唱","SING"),
JUMP("跳","JUMP"),
RAP("Rap","RAP"),
OTHER("未知","OTHER");
private String word;
private String type;
HobbyEnum(String word, String type){
this.word = word;
this.type = type;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
直接使用會報錯
解決方案
修改枚舉類
新增一個靜態方法,getByType()
enum HobbyEnum{
SIGN("唱","SING"),
JUMP("跳","JUMP"),
RAP("Rap","RAP"),
OTHER("未知","OTHER");
private String word;
private String type;
HobbyEnum(String word, String type){
this.word = word;
this.type = type;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public static HobbyEnum getByType(String type){
for (HobbyEnum constants : values()) {
if (constants.getType().equalsIgnoreCase(type)) {
return constants;
}
}
return OTHER;
}
}
修改實現邏輯
使用的時候直接根據type去獲取這個枚舉,這樣就可以進行判斷了