1. 应用场景场景描述:
项目重构,要匹配交易类型处理数据.交易类型的字段类型为String,最初是在switch中直接使用String类型匹配.
为了提升代码的可靠性与重用性,这里将String类型换成枚举类.每次传进来的String,首先处理成枚举类进行匹配.
2. 源码如下:
public enum TransactionType {
P_1000("1000"),
P_1001("1001"),
P_1002("1002"),
P_1003("1003"),
P_1004("1004");
private String transactionType;
private TransactionType(String transactionType){
this.transactionType = transactionType;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
//用于switch中,将String转化为枚举类
public static TransactionType getByType(String type){
for (TransactionType transactionType:values()) {
if (transactionType.getTransactionType().equals(type)) {
return transactionType;
}
}
return null;
}
//测试代码
public static void main(String[] args) {
switch (TransactionType.getByType("1000")) {
case P_1000:
System.out.println("------ok啦----");
break;
case P_1001:
System.out.println("------哭啦----");
break;
default:
System.out.println("------摔啦----");
break;
}
}
}
网友评论