以前也遇到过类似的问题。就是对于一些参数,比如type之类的,对不同的type需要进行不同的处理。
对于这种情况,使用switch应该算是最恰当的了,但问题是switch并不支持String类型(听说Java8能支持了),所以当type是一个String对象时,就只能不断的if/else if/else了。
在这个时候,枚举类型就派上用场了。我们可以通过创建一个包含相关type的枚举类来解决问题。
package enumlation;
public enum TypeEnum {
type1, type2, type3;
public static boolean contains(String type){
for(TypeEnum typeEnum : TypeEnum.values()){
if(typeEnum.name().equals(type)){
return true;
}
}
return false;
}
public static void main(String[] args){
String type = "type";
TypeEnum typeEnum;
if(!TypeEnum.contains(type)){
typeEnum = TypeEnum.type1;
}
else{
typeEnum = TypeEnum.valueOf(type);
}
switch (typeEnum) {
case type1:
System.out.println("do type1");
break;
case type2:
System.out.println("do type2");
break;
case type3:
System.out.println("do type3");
break;
default:
break;
}
}
}
通过这种方式,就可以很好的解决String的switch判断。另外,还可以通过在枚举类中添加自定义的属性和方法来达成一些其他的目的。