File tree 1 file changed +52
-0
lines changed
1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ ##如何将String转换为enum
2
+
3
+
4
+
5
+ ### 问题
6
+ 一个枚举定义:
7
+
8
+ ``` java
9
+ public enum Blah {
10
+ A , B , C , D
11
+ }
12
+ ```
13
+ 并且我知道枚举的String值,比如 "A",我想将其转换为Blah.A,我应该怎么做?
14
+ 是否有Enum.valueOf() 这样的方法,如果是,那我如何使用?
15
+
16
+
17
+ ### 答案
18
+ 是的,Blah.valueOf("A") 将会得到 Blah.A
19
+
20
+ 静态方法valueOf() 和 values() 会在编译期创建,不过这不会体现在源代码内,他们出现在JavaDoc中,比如 [ Dialog.ModalityTyp] ( http://docs.oracle.com/javase/7/docs/api/java/awt/Dialog.ModalityType.html ) 中出现这两个方法。
21
+
22
+ ### 其他答案
23
+
24
+ 我有一个友善的工具方法:
25
+ ``` java
26
+ /**
27
+ * A common method for all enums since they can't have another base class
28
+ * @param <T> Enum type
29
+ * @param c enum type. All enums must be all caps.
30
+ * @param string case insensitive
31
+ * @return corresponding enum, or null
32
+ */
33
+ public static < T extends Enum<T > > T getEnumFromString(Class<T > c, String string) {
34
+ if ( c != null && string != null ) {
35
+ try {
36
+ return Enum . valueOf(c, string. trim(). toUpperCase());
37
+ } catch (IllegalArgumentException ex) {
38
+ }
39
+ }
40
+ return null ;
41
+ }
42
+ ```
43
+
44
+ 你可以这么使用:
45
+
46
+ ``` java
47
+ public static MyEnum fromString(String name) {
48
+ return getEnumFromString(MyEnum . class, name);
49
+ }
50
+ ```
51
+
52
+ stackoverflow链接:http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java
You can’t perform that action at this time.
0 commit comments