Java 列舉 switch的用法
阿新 • • 發佈:2018-11-12
因有個判斷需要處理不同系統型別跳轉不同 系統。 考慮用switch + 列舉的方式。 具體使用案例如下:
package com.b2b.common.constant; import com.base.utils.base.StringUtils; /** * 系統型別列舉 * @author shijing */ public enum SystemType { ERP(0,"ERP"), ORDER_PLATFORM(1,"訂貨平臺"), PERSONAL(2,"個人中心繫統"), SHOP_MALL(3,"商城"), PARTNER(4,"夥伴系統"); private int value; private String desc; SystemType(int value ,String desc) { this.value = value; this.desc = desc; } public int getValue() { return value; } public String getDesc() { return desc; } /** * 通過value取列舉 * @param value * @return */ public static SystemType getTypeByValue(String value){ if (StringUtils.isNull(value)){ return null; } int valueKey = Integer.parseInt(value); for (SystemType enums : SystemType.values()) { if (enums.getValue() == valueKey) { return enums; } } return null; } /** * 通過value取描述 * @param value * @return */ public static String getDescByValue(int value) { for (SystemType enums : SystemType.values()) { if (enums.getValue() == value) { return enums.getDesc(); } } return ""; } }
switch+列舉的使用案例:
/** * 區分不同系統型別,登入不同系統 * @author shijing * @param paramMap * @param checkData * @return * @throws Exception */ private ErpResponse getLoginResponse(Map<String, Object> paramMap, ErpResponse checkData) throws Exception { ErpResponse loginData = null; Map<String,Object> user= (Map<String, Object>) checkData.getData(); //獲取user的系統型別,然後區分是哪個系統例項使用者登入 String sysBaseType = (String) user.get("sys_base_type"); SystemType systemType = SystemType.getTypeByValue(sysBaseType); switch(systemType){ case ERP: erpLogin((String) user.get("user_id")); loginData.setData(user); break; case ORDER_PLATFORM: //訂貨平臺 orderPlatformLoginByCheck(paramMap); loginData.setData(user); break; case PERSONAL: //個人中心 loginData = personalLogin(user); break; default: LOGGER.info("系統型別不滿足"); break; } return loginData; }