将空字符串传递给 Java 枚举 .valueOf 调用时会产生什么结果?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/904546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:52:59  来源:igfitidea点击:

What results when you pass an empty string to a Java enum .valueOf call?

javaenums

提问by Jay R.

What results when you pass an empty string to a Java enum .valueOf call?

将空字符串传递给 Java 枚举 .valueOf 调用时会产生什么结果?

For example:

例如:

public enum Status
{
   STARTED,
   PROGRESS,
   MESSAGE,
   DONE;
}

and then

进而

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");
   }
}

Basically, I want to know if I'm using a switch statement with the enum, will the default case be called or will I get an exception of some sort?

基本上,我想知道我是否在 enum 中使用 switch 语句,会调用默认情况还是会得到某种异常?

采纳答案by Tom Hawtin - tackline

You should get an IllegalArgumentExceptionif the name is not that of an enum (which it wont be for the empty string). This is generated in the API docs for all enum valueOfmethods. You should get a NullPointerExceptionfor null. It's probably not a good idea to give a dummy value to your Stringvariable (nor to allow the last case/defaultto fall through).

IllegalArgumentException如果名称不是枚举的名称(对于空字符串则不会),您应该得到一个。这是在所有枚举valueOf方法的 API 文档中生成的。你应该得到一个NullPointerExceptionfor null。为您的String变量提供一个虚拟值可能不是一个好主意(也不允许最后一个case/default失败)。

回答by Etienne de Martel

I just tried your code. It throws an IllegalArgumentException. Just like the documentation says.

我刚刚试过你的代码。它抛出一个IllegalArgumentException. 就像文档说的那样。

回答by Peter Lawrey

Status.valueOf behaves the same as Enum.valueOf

Status.valueOf 的行为与Enum.valueOf相同

回答by sazamsk

method: valueOf

方法: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**

so it will flag these exceptions,

所以它会标记这些异常,