创建枚举类 PersonEnum.java
import java.util.ArrayList;
import java.util.List;
public enum PersonEnum {
PERSON_NAME("name","姓名"),
PERSON_AGE("age","年龄"),
PERSON_GENDER("gender","性别");
PersonEnum(String code, String name) {
this.code = code;
this.name = name;
}
private String code;
private String name;
/**
* 通过code获取name
* @param code
* @return
*/
public static String getNameByCode(String code){
for(PersonEnum personEnum : PersonEnum.values()){
if(personEnum.code.equals(code)){
return personEnum.name;
}
}
return null;
}
/**
* 通过name获取code
* @param name
* @return
*/
public static String getCodeByName(String name){
for(PersonEnum personEnum : PersonEnum.values()){
if(personEnum.name.equals(name)){
return personEnum.code;
}
}
return null;
}
/**
* 通过code获取PersonEnum
* @param code
* @return
*/
public static PersonEnum getPersonEnumByCode(String code){
for(PersonEnum personEnum : PersonEnum.values()){
if(personEnum.code.equals(code)){
return personEnum;
}
}
return null;
}
/**
* 通过name获取PersonEnum
* @return
*/
public static PersonEnum getPersonEnumByName(String name){
for(PersonEnum personEnum : PersonEnum.values()){
if(personEnum.name.equals(name)){
return personEnum;
}
}
return null;
}
/**
* 获取所有codes
* @return
*/
public static List<String> getAllCodes(){
List<String> codes = new ArrayList<>();
for(PersonEnum personEnum : PersonEnum.values()){
codes.add(personEnum.code);
}
return codes;
}
/**
* 获取所有names
* @return
*/
public static List<String> getAllNames(){
List<String> codes = new ArrayList<>();
for(PersonEnum personEnum : PersonEnum.values()){
codes.add(personEnum.name);
}
return codes;
}
public static void main(String[] args){
String age = getNameByCode("age");
System.out.println("获取age的name值:"+age);
String name =getCodeByName("姓名");
System.out.println("获取name的code值:"+name);
PersonEnum agePersonEnum = getPersonEnumByCode("age");
System.out.println("获取age的PersonEnum值:"+agePersonEnum.code+"----"+agePersonEnum.name);
PersonEnum namePersonEnum = getPersonEnumByName("姓名");
System.out.println("获取name的namePersonEnum值:"+namePersonEnum.code+"----"+namePersonEnum.name);
List<String> codeList = getAllCodes();
System.out.println("获取所有code值:"+codeList);
List<String> nameList = getAllNames();
System.out.println("获取所有name值:"+nameList);
}
}
运行结果:
获取age的name值:年龄
获取name的code值:name
获取age的PersonEnum值:age----年龄
获取name的namePersonEnum值:name----姓名
获取所有code值:[name, age, gender]
获取所有name值:[姓名, 年龄, 性别]
Process finished with exit code 0