美文网首页
Java-在switch中使用枚举类

Java-在switch中使用枚举类

作者: GuangHui | 来源:发表于2018-05-28 12:23 被阅读19次

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;
        }
        
    }
}

相关文章

网友评论

      本文标题:Java-在switch中使用枚举类

      本文链接:https://www.haomeiwen.com/subject/lqzwjftx.html