赞
踩
例一:
public static enum WeChatRecordMsgType { EVENT("event"), TEXT("text"), IMAGE("image"), VOICE("voice"), VIDEO("video"); private final String msgType; WeChatRecordMsgType(String msgType) { this.msgType = msgType; } public static WeChatRecordMsgType msgTypeValueOf(String msgType) { switch (msgType) { case "event": return EVENT; case "text": return TEXT; case "image": return IMAGE; case "voice": return VOICE; case "video": return VIDEO; default: return null; } } }
类中调用:
final WeChatRecordMsgType type = WeChatRecordMsgType.msgTypeValueOf(inMessage.getMsgType()); switch (type) { case EVENT: content = inMessage.getEventKey(); break; case TEXT: content = inMessage.getContent(); break; case VOICE: case VIDEO: case IMAGE: content = inMessage.getMediaId(); break; default: throw new WrongCodeError("type字段有误:" + type); }
例二
public enum HomeworkType { PreviewBeforeClass(2, "课前导学"), HomeworkAfterClass(1, "课后作业"); private final int type; private final String meaning; private HomeworkType(int type, String meaning) { this.type = type; this.meaning = meaning; } public static HomeworkType valueOf(int type) { switch (type) { case 1: return HomeworkAfterClass; case 2: return PreviewBeforeClass; default: return null; } } }
枚举的使用:初始化,构造函数,避免空指针
public enum APPType { WYS_STUDENT, WYS_TEACHER, RJS_STUDENT, QT;// 其他 static public APPType fromString(String type) { //格式化枚举类 if (type != null) { try { return APPType.valueOf(type.trim().toUpperCase()); } catch (IllegalArgumentException ex) { } } return APPType.QT; } public static APPType getValidAppType(APPType appType) { //使用枚举前,调用:反初始值 if (null == appType) { return WYS_STUDENT; } switch (appType) { case WYS_STUDENT: case WYS_TEACHER: return WYS_STUDENT; case RJS_STUDENT: case RJS_TEACHER: return RJS_STUDENT; default: return appType; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。