Подтвердить что ты не робот

Какие результаты при передаче пустой строки в вызов Java enum.valueOf?

Какие результаты при передаче пустой строки в вызов Java enum.valueOf?

Например:

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

а затем

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

В принципе, я хочу знать, могу ли я использовать оператор switch с перечислением, будет ли вызван случай по умолчанию или я получу какое-то исключение?

4b9b3361

Ответ 1

Вы должны получить IllegalArgumentException, если имя не относится к перечислению (которое оно не будет для пустой строки). Это генерируется в документах API для всех методов enum valueOf. Вы должны получить NullPointerException для null. Вероятно, неплохо дать фиктивное значение вашей переменной String (и не позволить пропустить последний case/default).

Ответ 2

Я просто попробовал свой код. Он выбрасывает IllegalArgumentException. Так же, как говорится в документации.

Ответ 3

Status.valueOf ведет себя так же, как Enum.valueOf

Ответ 4

метод: значениеOf

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**

поэтому он будет отмечать эти исключения,