当前位置:   article > 正文

如何在 switch case 中使用枚举类_java switch case值能为枚举值吗

java 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----------");
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

运行结果如下:

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;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

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

public static TypeEnnum getTypeName(String type){
        for(TypeEnnum transactType : values()){
            if (transactType.getType().equals(type)) {
                //获取指定的枚举
                return transactType;
            }
        }
        return null;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/729143
推荐阅读
相关标签
  

闽ICP备14008679号