Java switch 中使用枚举

问题

想使用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去获取这个枚举,这样就可以进行判断了

猜你喜欢

转载自www.cnblogs.com/codeclock/p/12564924.html