1.功能需求
if else判断时写代码过程中非常常见的,但是有些相对比较固定格式的if else判断却是我们可以尽可能避免的,其中,枚举
的作用在我们消除if else代码快的作用非常大,那么,我们该如何实现呢?
2. 代码实现
- 定义枚举变量
import lombok.Getter; /** * @author wxz * 问卷授权枚举 */ public enum AuthorTypeEnum { ANONYMITY("0","匿名"), USER("1","用户"), ROLE("2","角色") , ORGANIZE("3","组织机构") ; /** * 审核状态 */ @Getter private final String code; /** * 描述 */ @Getter private final String description; AuthorTypeEnum(String code, String description) { this.code = code; this.description = description; } public static AuthorTypeEnum of(String code) { if (code == null) { return null; } AuthorTypeEnum[] values = AuthorTypeEnum.values(); for (AuthorTypeEnum a : values) { if (a.code.equals(code)) { return a; } } return null; } }
- 使用枚举
Questionnaire com = mapper.xxx(id); if (com == null) { throw new BusinessException("问卷对象为空,操作失败"); } Map<String, String> map = new HashMap<>(); //根据权限类型查询授权对象 if (StringUtil.isNotEmpty(com.getAuthorId())) { switch (AuthorTypeEnum.of(com.getAuthorId())) { case USER: // do something break; case ROLE: // do something break; case ORGANIZE: // do something default: break; } }
以上就是使用 枚举 + switch
配合使用消除比较固定格式的if else 代码判断了.
其中,最重要的就是 枚举变量的 of()
方法,这个方法的作用是:根据枚举code查询出对应的枚举对象
,这样我们就可以不用烦人的if else if代码块判断了.