介绍
Java8 开始 Switch中可以使用String;为了提升代码的可靠性与重用性,可以将String类型换成枚举类,每次将String入参处理成枚举类再进行匹配;
实际开发任务中很多使用也会在Switch中使用枚举类,此处做个总结;
1、枚举类
MsgTypeEnums
枚举类中有两个字段:tableName、msgType:
@Getter
public enum MsgTypeEnums {/*** 大件正向*/BIG_TICKET_NORMAL("table1", "BIG_TICKET_NORMAL"),/*** 小件正向*/SMALL_TICKET_NORMAL("table2", "SMALL_TICKET_NORMAL"),/*** 大件取消*/BIG_TICKET_CANCEL("table3", "BIG_TICKET_CANCEL"),/*** 小件取消*/SMALL_TICKET_CANCEL("table4", "SMALL_TICKET_CANCEL"),/*** 大件退货*/BIG_TICKET_RETURN("table5", "BIG_TICKET_RETURN"),/*** 小件退货*/SMALL_TICKET_RETURN("table6", "SMALL_TICKET_RETURN"),/*** 撤销交易*/RESCIND_TRADE("table7", "RESCIND_TRADE");/*** 表名*/private String tableName;/*** 消息类型*/private String msgType;MsgTypeEnums(String tableName, String msgType) {this.tableName = tableName;this.msgType = msgType;}public static MsgTypeEnums getMsgType(String msgType) {for (MsgTypeEnums value : MsgTypeEnums.values()) {if (value.msgType.equalsIgnoreCase(msgType)) {return value;}}// 理论上不会走进这里throw new IllegalArgumentException("unknown msgType:" + msgType);}
}
2、Switch语句
public void testMsgType(String msgType) {MsgTypeEnums msgType = MsgTypeEnums.getMsgType(msgType);switch (msgType) {case BIG_TICKET_NORMAL:// do somethingSystem.out.println("----");break;case SMALL_TICKET_NORMAL:// do somethingbreak;default:throw new IllegalArgumentException("unsupported.");}}
注意:case上使用的是枚举类型,不需要加枚举类类名;而switch输入枚举类实例。
3、源码中的使用
前一段时间看seata源码,隐约记得它有用过,如下;
1> 枚举类:
2> switch语句: