我有以下示例情况:
public void shouldReturnStringForEnum() {
MessageType myType = getType();
System.out.println(getMessageForType(myType));
}
String getMessageForType(MessageType myType) {
switch(myType) {
case error:
return "Error type";
case warning:
return "Warning type";
case info:
return "Info type";
}
} // <= error: missing return statement
MessageType getType() {
Random random = new Random();
return MessageType.values()[random.nextInt(3)];
}
enum MessageType {error, warning, info }
除了 switch
语句的主体之外,我无法弄清楚从方法 getMessageForType
返回的可能性有多大。
我在想:
- 从 I/O 数据反序列化 - 但是
java.lang.IllegalArgumentException: No enum constant
在调用getMessageForType
之前很久就发生了 - 可能是 null 方法参数 - 但它会在
switch(myType)
评估时失败,并出现java.lang.NullPointerException
在这种情况下强制使用默认返回语句是不舒服的,因为我不知道在这里返回什么。在这种情况下抛出异常在这里也没有意义。这种行为背后的设计决策是什么?
请帮忙,我在这里缺少什么?
最佳答案
如果您稍后编辑枚举,添加一个新常量,而不重新编译开关,会发生什么情况?就是要提防这种情况。
编写 default: throw new AssertionError();
是完全正常的。
关于Java强制使用枚举开关从方法返回默认语句,并覆盖所有枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641541/