File tree Expand file tree Collapse file tree 1 file changed +33
-1
lines changed Expand file tree Collapse file tree 1 file changed +33
-1
lines changed Original file line number Diff line number Diff line change @@ -19,6 +19,38 @@ Enum.valueOf()是否能实现以上目的,如果是,那我如何使用?
19
19
20
20
### 其他答案
21
21
22
+ 当文本和枚举值不同时,可以采用这种方式:
23
+ ``` java
24
+ public enum Blah {
25
+ A (" text1" ),
26
+ B (" text2" ),
27
+ C (" text3" ),
28
+ D (" text4" );
29
+
30
+ private String text;
31
+
32
+ Blah (String text ) {
33
+ this . text = text;
34
+ }
35
+
36
+ public String getText () {
37
+ return this . text;
38
+ }
39
+
40
+ public static Blah fromString (String text ) {
41
+ for (Blah b : Blah . values()) {
42
+ if (b. text. equalsIgnoreCase(text)) {
43
+ return b;
44
+ }
45
+ }
46
+ return null ;
47
+ }
48
+ }
49
+ ```
50
+ fromString方法中,throw new IllegalArgumentException("No constant with text " + text + " found") 会比直接返回null更优秀.
51
+
52
+ ### 其他答案
53
+
22
54
我有一个挺赞的工具方法:
23
55
``` java
24
56
/**
@@ -47,4 +79,4 @@ public static MyEnum fromString(String name) {
47
79
}
48
80
```
49
81
50
- stackoverflow链接:http://stackoverflow.com/questions/604424/convert-a-string-to-an-enum-in-java
82
+ 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