枚举的简单使用如下:
根据code获取name
public static String getName(Integer code){
for(TestEunm testEunm : TestEunm.values()){
if(testEunm.code.equals(code)){
return testEunm.name;
}
}
return null;
}
获取全部枚举:
public static List<CommonEunm> getList(){
List<CommonEunm> eunmList = Lists.newArrayList();
for (TestEunm testEunm : TestEunm.values()){
//创建一个有name和code的类
CommonEunm commonEunm = new CommonEunm();
commonEunm.setCode(testEunm.code);
commonEunm.setName(testEunm.name);
eunmList.add(commonEunm);
}
return eunmList;
}
完整代码:
package com.info.eunmUtils;
import com.info.Vo.CommonEunm;
import org.assertj.core.util.Lists;
import java.util.List;
public enum TestEunm {
ONES("第一",10),
TWOS("第二",20),
THREES("第三",30),
FOURS("第四",40);
private Integer code;
private String name;
public Integer getCode() {
return code;
}
public String getName() {
return name;
}
TestEunm(String name, Integer code) {
this.code = code;
this.name = name;
}
/**
*根据code查找name(根据name查找code同理)
* @return
*/
public static String getName(Integer code){
for(TestEunm testEunm : TestEunm.values()){
if(testEunm.code.equals(code)){
return testEunm.name;
}
}
return null;
}
/**
* 获取全部枚举
*/
public static List<CommonEunm> getList(){
List<CommonEunm> eunmList = Lists.newArrayList();
for (TestEunm testEunm : TestEunm.values()){
//创建一个有name和code的类
CommonEunm commonEunm = new CommonEunm();
commonEunm.setCode(testEunm.code);
commonEunm.setName(testEunm.name);
eunmList.add(commonEunm);
}
return eunmList;
}
}