switch…case本身支持的变量类型有 :int、byte、short、char、string。
官方解释:
也就是说本身switch是不支持枚举的,需要做一定的转换
代码示例:
public enum Annonation {
A("A", ""),
B("B", "");
private String code;
private String desc;
Annonation(String code, String desc) {
this.code = code;
this.desc = desc;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
//字符串转枚举方法
public static Optional<Annonation> getLoanTypeEnum(String type) {
return Arrays.stream(Annonation.values()).filter(e -> e.getCode().equalsIgnoreCase(type)).findFirst();
}
public static void main(String[] args) {
Optional<Annonation> loanTypeEnum = getLoanTypeEnum("A");
/*typeEnum转换失败 不能执行switch case 否则会抛出异常java.util.NoSuchElementException: No value present
或者给typeEnum一个默认值
*/
if (!typeEnum.isPresent()){
//typeEnum.orElse(Annonation.A);
return;
}
switch (loanTypeEnum.get()) {
case A:
System.out.println(A);
break;
case B:
System.out.println(B);
break;
default:
System.out.println("default");
break;
}
}
}