【Java】【7】枚举类
用处:规范了参数的形式,更简洁易懂
实例:
//消息类型 public enum MessageTypeEnum { AdminReward(1, "官方消息"), StoreReward(2, "答题奖励"), QuarterReward(3, "季度获奖"), YearReward(4, "年度获奖"); private int index; private String name; private MessageTypeEnum(int index, String name) { this.index = index; this.name = name; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static String getName(int index) { for (MessageTypeEnum item : MessageTypeEnum.values()) { if (item.getIndex() == index) { return item.getName(); } } return ""; } }
在代码中的应用
//根据情况给int类型的字段复值 info.setType(MessageTypeEnum.AdminReward.getIndex()); //避免了1,2,3这种魔鬼数字 //根据int的值,获得对应String类型的值 int type = 1; String name = MessageTypeEnum.getName(type); //转成list public List<MessageVo> getPositionList() { List<MessageVo> list = new ArrayList<MessageVo>(); for (MessageTypeEnum item : MessageTypeEnum.values()) { MessageVo info = new MessageVo(); info.setType(item.getIndex()); info.setName(item.getName()); list.add(info); } return list; }