如何在 switch case 中使用枚举类

在JDK 5中加入的枚举Enum类型也是可以作为case值的。
在JDK 7中,又加入了对String类型的支持,从此不用再写If-Else来判断字符串了。

switch的case语句可以处理int,short,byte,char类型的值,
因为short,byte,char都会转换成int进行处理,这一点也可以从生成的字节码看出。

下面举例。如何在switch-case中使用ennum枚举类型:

public class SwitchEnumDemo {
    
    
    public static void main(String[] args) {
    
    
        String type = "type1";
        switch (Objects.requireNonNull(TypeEnnum.getTypeName(type))) {
    
    
            case TYPE_1:
                System.out.println("type1----------");
                break;
            case TYPE_2:
                System.out.println("type2----------");
                break;
            case TYPE_3:
                System.out.println("type3----------");
                break;
            default:
                System.out.println("defualt---type----------");
        }
    }

}

运行结果如下:

type

定义枚举类如下:
```javascript
public enum TypeEnnum {
    
    
    TYPE_1("type1", "类型1"),
    TYPE_2("type2", "类型2"),
    TYPE_3("type3", "类型3"),
    ;

    TypeEnnum(String type, String desc) {
    
    
        this.type = type;
        this.desc = desc;

    }

    private String type;
    private String desc;

    public String getType() {
    
    
        return type;
    }

    public String getDesc() {
    
    
        return desc;
    }

    public static TypeEnnum getTypeName(String type){
    
    
        for(TypeEnnum transactType : values()){
    
    
            if (transactType.getType().equals(type)) {
    
    
                //获取指定的枚举
                return transactType;
            }
        }
        return null;
    }
}

注意枚举类中需要以下方法:

public static TypeEnnum getTypeName(String type){
    
    
        for(TypeEnnum transactType : values()){
    
    
            if (transactType.getType().equals(type)) {
    
    
                //获取指定的枚举
                return transactType;
            }
        }
        return null;
    }

否则会报如下错误,识别不出枚举类型:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_37899908/article/details/131029481