将空字符串传递给Java枚举.valueOf调用时会出现什么结果?
例如:
public enum Status
{
STARTED,
PROGRESS,
MESSAGE,
DONE;
}
Run Code Online (Sandbox Code Playgroud)
然后
String empty = "";
switch(Status.valueOf(empty))
{
case STARTED:
case PROGRESS:
case MESSAGE:
case DONE:
{
System.out.println("is valid status");
break;
}
default:
{
System.out.println("is not valid");
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我想知道我是否使用带有枚举的switch语句,是否会调用默认情况,还是会得到某种异常?
Tom*_*ine 50
你应该得到一个IllegalArgumentException如果名称不是枚举的名称(它不是空字符串).这是在所有枚举valueOf方法的API文档中生成的.你应该得到NullPointerException的null.给String变量赋一个虚拟值可能不是一个好主意(也不允许最后一个case/ default掉头).
我刚试过你的代码.它抛出一个IllegalArgumentException.就像文档说的那样.
小智 5
方法:valueOf
Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
Parameters:
enumType - the Class object of the enum type from which to return a constant
name - the name of the constant to return
Returns:
the enum constant of the specified enum type with the specified name
Throws:
IllegalArgumentException - if the specified enum type has no constant with the specified name, or **the specified class object does not represent an enum type**
NullPointerException - if **enumType or name is null**
Run Code Online (Sandbox Code Playgroud)
所以它会标记这些异常,
| 归档时间: |
|
| 查看次数: |
48355 次 |
| 最近记录: |