Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 01b6166

Browse files
Merge pull request giantray#87 from v2hoping/patch-1
更新了convert-a-string-to-an-enum-in-java,增加了一种常用回答
2 parents 08d195f + 3fc6af0 commit 01b6166

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

‎contents/convert-a-string-to-an-enum-in-java.md

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,38 @@ Enum.valueOf()是否能实现以上目的,如果是,那我如何使用?
1919

2020
### 其他答案
2121

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+
2254
我有一个挺赞的工具方法:
2355
```java
2456
/**
@@ -47,4 +79,4 @@ public static MyEnum fromString(String name) {
4779
}
4880
```
4981

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /