java的字符串转枚举类型

假定一个美酒类型

1
PizzaStatusEnum readyStatus = PizzaStatusEnum.READY;

使用 valueOf(“”)方法

1
2
3
4
5
6
7
8
@Test
public void whenConvertedIntoEnum_thenGetsConvertedCorrectly() {

String pizzaEnumValue = "READY";
PizzaStatusEnum pizzaStatusEnum
= PizzaStatusEnum.valueOf(pizzaEnumValue);
assertTrue(pizzaStatusEnum == PizzaStatusEnum.READY);
}

注意: 如果参数不对,会抛出非法参数异常

1
2
3
4
5
@Test(expected = IllegalArgumentException.class)
public void whenConvertedIntoEnum_thenThrowsException() {
String pizzaEnumValue = "invalid";
PizzaStatusEnum pizzaStatusEnum = PizzaStatusEnum.valueOf(pizzaEnumValue);
}
分享到