枚举类中枚举值不存在.valueOf(enum) 抛异常处理
开发过程中,经常使用枚举类操作一些分支情况,但是当入参在枚举类中找不到时,就会抛异常,没办法进行 if(lbAppHomeOperator == null) 操作,这时我们可以使用 Enums.getIfPresent(XXXEnum.class, strEnum).orNull(); 进行处理。
*****业务代码:
1、枚举类
/** * @author D-L * @program: ella-server * @description: 听书首页发布操作 * @date 2021-01-12 11:24:18 */ @Slf4j public enum PublishLbAppHomeOperator { APPCN { @Override public void apply(LbListenMapper lbListenMapper) { lbListenMapper.publishLbHomePageAppCn(); log.info("国内app听书首页发布成功"); } }, APPOTHER { @Override public void apply(LbListenMapper lbListenMapper) { lbListenMapper.publishLbHomePageAppOther(); log.info("其他地区app听书首页发布成功"); } }, HDCN { @Override public void apply(LbListenMapper lbListenMapper) { lbListenMapper.publishLbHomePageHdCn(); log.info("国内HD听书首页发布成功"); } }, HDOTHER { @Override public void apply(LbListenMapper lbListenMapper) { lbListenMapper.publishLbHomePageHdOther(); log.info("其他地区HD听书首页发布成功"); } }, GUSHIJI { @Override public void apply(LbListenMapper lbListenMapper) { lbListenMapper.publishLbHomePageGushiji(); log.info("故事机听书首页发布成功"); } }; public abstract void apply(LbListenMapper lbListenMapper); }
2、提供一个 getIfPresent 判断方法
/** * 判断枚举类中 是否存在传入的枚举值 * @param operatorEnum * @return */ private PublishLbAppHomeOperator getIfPresent(String operatorEnum) { return Enums.getIfPresent(PublishLbAppHomeOperator.class, operatorEnum).orNull(); }
3、具体调用
if(getIfPresent(operatorEnum) == null){ log.info("platformCode , siteCode --- check param error :{} , {}", platformCode , siteCode); response.setCodeAndMessage(PARAM_ERROR_CODE, PARAM_ERROR_DESC); return; }