We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 08d195f + 3fc6af0 commit 01b6166Copy full SHA for 01b6166
contents/convert-a-string-to-an-enum-in-java.md
@@ -19,6 +19,38 @@ Enum.valueOf()是否能实现以上目的,如果是,那我如何使用?
19
20
### 其他答案
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
54
我有一个挺赞的工具方法:
55
```java
56
/**
@@ -47,4 +79,4 @@ public static MyEnum fromString(String name) {
79
}
80
```
81
-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
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments