Java枚举实战
枚举的应用在项目中比较常见,当一个变量有几种固定可能的取值时,就可以将它定义成一个枚举。下面拿小说种类来定义一个枚举。
假设小说的种类有6种:武侠小说、推理小说、悬疑小说、历史小说、军事小说、言情小说。
public enum NovelEnum { MARTIAL(0,"武侠小说"), MYSTERY(1,"推理小说"), SUSPENSE(2,"悬疑小说"), HISTORICAL(3,"历史小说"), MILITARY(4,"军事小说"), ROMANCE(5,"言情小说"); private final Integer code; private final String type; NovelEnum(Integer code,String type){ this.code = code; this.type = type; } public Integer getCode() { return code; } public String getType() { return type; } public static String getType(Integer code){ for (NovelEnum novel : NovelEnum.values()){ if (novel.code == code){ return novel.type; } } return ""; } public static String getName(Integer code){ for (NovelEnum novel : NovelEnum.values()){ if (novel.code == code){ return novel.name(); } } return ""; } public static Integer getCode(String type){ if (StringUtil.isBlank(type)){ return null; } for (NovelEnum novel: NovelEnum.values()){ if (novel.type.equals(type)){ return novel.code; } } return null; } public static List<NovelEnum> getEnumVo(){ List<NovelEnum> enums = new ArrayList<>(); for (NovelEnum novel : NovelEnum.values()){ enums.add(novel); } return enums; } }
为了用一下这个枚举,我们再定义一个小说实体类Novel.java
public class Novel { private Integer id; private String name; private Integer typeCode; private String typeName; private Integer authId; private String authName; public Novel( String name, String typeName, Integer authId, String authName) { this.id = new Random().nextInt(1000); this.name = name; this.typeCode = NovelEnum.getCode(typeName); this.typeName = typeName; this.authId = authId; this.authName = authName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getTypeCode() { return typeCode; } public void setTypeCode(Integer typeCode) { this.typeCode = typeCode; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } public Integer getAuthId() { return authId; } public void setAuthId(Integer authId) { this.authId = authId; } public String getAuthName() { return authName; } public void setAuthName(String authName) { this.authName = authName; } @Override public String toString() { return "Novel{" + "id=" + id + ", name='" + name + '\'' + ", typeCode=" + typeCode + ", typeName='" + typeName + '\'' + ", authId=" + authId + ", authName='" + authName + '\'' + '}'; } }
public class NovelEnumTest { public static void main(String[] args) { Novel novel = new Novel("斗破苍穹",NovelEnum.MARTIAL.getType(),112,"唐家三少"); Novel novel2 = new Novel("鬼吹灯",NovelEnum.SUSPENSE.getType(),225,"南派三叔"); System.out.println(novel); System.out.println(novel2); } }
有几个注意的点
①Enum的属性应该都是不可变的。
②一般情况下Enum的操作方法,比如上文的getName、getType、getCode都是静态方法,这样方便我们在操作中使用,至于你想定义哪些方法随你便。
                    
                
                
            
        
浙公网安备 33010602011771号