一. Enum的通用写法
- 最近项目中Enum类的使用较多,借此机会将Enum类的常用方法和编程写法总结如下。
public enum TypeEnum {
TYLE_1("1","类型1"),
TYPE_2("2","类型2"),
TYPE_3("3","类型3");
TypeEnum(String code , String value){
this.code = code ;
this.value = value ;
}
private String code;
private String value;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public static String getValueByCode(String code){
if(code == null){
return "";
}
for(TypeEnum typeEnum:TypeEnum.values()){
if(typeEnum.getCode().equals(code)){
return typeEnum.getValue();
}
}
return "";
}
public static TypeEnum getTypeEnumBytypeId(String code){
for(TypeEnum topType:values()){
if(topType.getCode().equals(code)){
return topType;
}
}
return null;
}
}
二. Enum在switch中的用法
- 特别注意:switch的case语句只能写枚举类定义的变量名,不能加类名。
- 错误范例
public static void testEnum(TypeEnum typeEnum){
switch (typeEnum){
case TypeEnum.TYLE_1:
System.out.println("type1");
break;
case TypeEnum.TYPE_2:
System.out.println("type2");
break;
case TypeEnum.TYPE_3:
System.out.println("type3");
break;
default:
System.out.println("其他");
break;
}
}
- 上述代码编译会报错:an enum switch case label must be the unqualified name of an enumeration constant。其意思是枚举的
switch...case
标签必须为枚举常量的非限定名称。
- 正确范例
public class EnumTest {
public static void main(String[] args) {
String type = "1";
TypeEnum typeEnum = TypeEnum.getTypeEnumBytypeId(type);
if(typeEnum!=null){
testEnum(typeEnum);
}
}
public static void testEnum(TypeEnum typeEnum){
switch (typeEnum){
case TYLE_1:
System.out.println("type1");
break;
case TYPE_2:
System.out.println("type2");
break;
case TYPE_3:
System.out.println("type3");
break;
default:
System.out.println("其他");
break;
}
}
}
- Tips:switch括号中的参数不能为null。如果swicth(null)会报java.lang.NullPointerException异常。
参考资料
如何在switch中使用enum