switch配合enum的使用

廢話不多說,先上代碼,拿性別舉個列子。

定義一個枚舉類

public enum SexEnum {
    ERROR("0", "錯誤的性別"),
    MAN("1", "男人"),
    WOMAN("2", "女人");

    String code;
    String name;

    //枚舉被設置成單例的,是不允許new的,所以構造方法默認是private修飾的
    SexEnum(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public static SexEnum getSexEnumByCode(String code){
        for(SexEnum sexEnum : SexEnum.values()){
            if(StringUtils.equals(code, sexEnum.getCode())){
                return sexEnum;
            }
        }

        return ERROR;

        /**
         * 因爲我們要結合switch使用,所以這裏不要return null
         * switch的對象是null時會拋出空指針異常
         * 我這裏定義了ERROR這個枚舉,當傳入的參數不可識別時,返回ERROR枚舉
         */
        //return null;
    }
}

使用方式:

public class Demo26 {
    public static void main(String[] args) {
        String sex = "1";
        switch (SexEnum.getSexEnumByCode(sex)){
            case MAN:
                System.out.println("this is a man");
                break;
            case WOMAN:
                System.out.println("this is a woman");
                break;
            default:
                System.out.println("maybe it's an alien");
                break;
        }
    }
}

如果if else分支比較多,選用switch case也是個不錯的方法。
這裏要注意的是switch的對象如果是null,會報空指針。枚舉類中多定了ERROR枚舉,是爲了讓getSexEnumByCode方法的入參是不能識別的編碼時,不要retrun null。這樣就能規避空指針的問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章