English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
在这个程序中,您将学习使用enum的valueOf()方法在Java中将字符串值转换为枚举。
public class EnumString { public enum TextStyle { BOLD, ITALICS, UNDERLINE, STRIKETHROUGH } public static void main(String[] args) { String style = "Bold"; TextStyle textStyle = TextStyle.valueOf(style.toUpperCase()); System.out.println(textStyle); } }
When running the program, the output is:
BOLD
In the above program, we have an enum TextStyle that represents the different styles that a text block can have, that is, bold, italic, underline, and strikethrough.
We also have a string named style that contains the current style we want. But not all of them are used.
Then, we use the valueOf() method of the enum TextStyle to pass the style and get the required enum value.
Since valueOf() takes a case-sensitive string value, we must use the toUpperCase() method to convert the given string to uppercase.
On the contrary, if we use:
TextStyle.valueOf(style)
This program will throw an exception No enum constant EnumString.TextStyle.Bold.