java中枚举用法
package com.sgcc.model;public enum EventsValueEnum {
MY_HITS("0001", "春眠不觉晓"),
RULE_HITS("0002", "处处闻啼鸟"),
SEARCH_HITS("0003", "夜来风雨声"),
TOTAL_ITEM_SHARE("0004", "花落知多少");
private String type;
private String msg;
private EventsValueEnum(String type, String msg) {
this.type = type;
this.msg = msg;
}
/**
* 根据code获取枚举名称
* @param type
* @return
*/
public static EventsValueEnum instance(String type) {
for (EventsValueEnum deviceAdType : EventsValueEnum.values()) {
if(deviceAdType.getType().equals(type)) {
return deviceAdType;
}
}
return null;
}
/**
* 根据code获取value
* @param type
* @return
*/
public static String getMsgByType(String type){
for(EventsValueEnum adTypeEnum:EventsValueEnum.values()){
if(type.equals(adTypeEnum.getType())){
return adTypeEnum.getMsg();
}
}
return null;
}
/**
* 根据name获取code
* @param msg
* @return
*/
public static String getTypeByMsg(String msg){
for(EventsValueEnum adTypeEnum:EventsValueEnum.values()){
if(msg.equals(adTypeEnum.getMsg())){
return adTypeEnum.getType();
}
}
return null;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
测试
public class NewOrder {public static void main(String[] args) {
String a="0001";
String b="0002";
String c="0003";
String d="0004";
String aa=DeviceAdTypeEnum.getMsgByType(a);
String bb=DeviceAdTypeEnum.getMsgByType(b);
String cc=DeviceAdTypeEnum.getMsgByType(c);
String dd=DeviceAdTypeEnum.getMsgByType(d);
System.out.println(aa+";");
System.out.println(bb+"。");
System.out.println(cc+";");
System.out.println(dd+"。");
}
}
打印
D:\work\java\jdk1.8\jdk1.8\jdk1.8.0_51\bin\java.exe "春眠不觉晓;
处处闻啼鸟。
夜来风雨声;
花落知多少。
Process finished with exit code 0
以上是 java中枚举用法 的全部内容, 来源链接: utcz.com/z/393112.html