Integer i = ...
switch (i){
case null:
doSomething0();
break;
}
在上面的代码中,我不能在switch case语句中使用null。我该怎么做呢?我无法使用,default因为那之后我想做点其他的事情。
Integer i = ...
switch (i){
case null:
doSomething0();
break;
}
在上面的代码中,我不能在switch case语句中使用null。我该怎么做呢?我无法使用,default因为那之后我想做点其他的事情。
Answers:
使用switchJava中的语句无法做到这一点。在null之前检查switch:
if (i == null) {
doSomething0();
} else {
switch (i) {
case 1:
// ...
break;
}
}
您不能在switch语句*中使用任意对象。究其原因,编译器不会抱怨switch (i)这里i是一个Integer是因为Java自动unboxes的Integer一个int。正如assylias已经说过的,拆箱将抛出NullPointerExceptionwhen iis null。
*从Java 7开始,您可以String在in switch语句中使用。
Oracle Docs中的更多信息switch(包括带有null变量的示例)-Switch
null使用String和enum类型时,这不可能是有效的情况,这似乎是不合理的。也许enum实现依赖于ordinal()在幕后进行调用(尽管如此,为什么不将null“序数”视为-1?),并且该String版本使用intern()和指针比较进行某些操作(或者依赖于严格要求取消引用的某些操作)。目的)?
鉴于:
public enum PersonType {
COOL_GUY(1),
JERK(2);
private final int typeId;
private PersonType(int typeId) {
this.typeId = typeId;
}
public final int getTypeId() {
return typeId;
}
public static PersonType findByTypeId(int typeId) {
for (PersonType type : values()) {
if (type.typeId == typeId) {
return type;
}
}
return null;
}
}
对我来说,这通常与数据库中的查找表对齐(仅适用于很少更新的表)。
但是,当我尝试findByTypeId在switch语句中使用(很可能是用户输入)时...
int userInput = 3;
PersonType personType = PersonType.findByTypeId(userInput);
switch(personType) {
case COOL_GUY:
// Do things only a cool guy would do.
break;
case JERK:
// Push back. Don't enable him.
break;
default:
// I don't know or care what to do with this mess.
}
...正如其他人所说,这将导致NPE @ switch(personType) {。我开始实施的一种解决方法(即“解决方案”)是添加一种UNKNOWN(-1)类型。
public enum PersonType {
UNKNOWN(-1),
COOL_GUY(1),
JERK(2);
...
public static PersonType findByTypeId(int id) {
...
return UNKNOWN;
}
}
现在,您不必进行空值检查,您可以选择是否处理UNKNOWN类型。(注意:-1在业务场景中是不太可能的标识符,但显然选择对您的用例有意义的内容)。
UNKNOWN是我见过的最好的解决方案,可以克服nullchecks。
您也可以使用String.valueOf((Object) nullableString)
像
switch (String.valueOf((Object) nullableString)) {
case "someCase"
//...
break;
...
case "null": // or default:
//...
break;
}
参见有趣的SO Q / A:为什么String.valueOf(null)抛出NullPointerException