|
| 1 | +#通过String值查找enum中常量 |
| 2 | +## 问题 |
| 3 | +假设有一个枚举值 |
| 4 | + public enum Blah |
| 5 | + { |
| 6 | + A,B,C,D |
| 7 | + } |
| 8 | +想通过一个String类型,找到所需要的枚举值。 |
| 9 | +例如"A"->Blah.A |
| 10 | +是使用Enum.valueOf()方法吗?该如何使用 |
| 11 | +## 回答 |
| 12 | +Blah.valueOf("A")会得到Blah.A |
| 13 | +虽然api文档确实有静态方法valueOf()和values(),但是二者在编译期时才出现,而且在没出现在源程序中。 |
| 14 | +例如可以采用Dialog.ModalityType显示了两种方法来处理这种情况。 |
| 15 | +备注:Blah.valueOf("A")的方法是区分大小写,且不能含有空格。 |
| 16 | + |
| 17 | +如果String值与enum中不相同的查找方法: |
| 18 | + |
| 19 | + public enum Blah |
| 20 | + { |
| 21 | + A("text1"), |
| 22 | + B("text2"), |
| 23 | + C("text3"), |
| 24 | + D("text4"); |
| 25 | + private String text; |
| 26 | + Blah(String text) |
| 27 | + { |
| 28 | + this.text = text; |
| 29 | + } |
| 30 | + public String getText() |
| 31 | + { |
| 32 | + return this.text; |
| 33 | + } |
| 34 | + |
| 35 | + public static Blah fromString(String text) |
| 36 | + { |
| 37 | + if (text != null) |
| 38 | + { |
| 39 | + for (Blah b : Blah.values()) |
| 40 | + { |
| 41 | + if (text.equalsIgnoreCase(b.text)) |
| 42 | + { |
| 43 | + return b; |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return null; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | +备注:throw new IllegalArgumentException("No constant with text"+text+"found")会比直接抛出null更好 |
| 52 | + |
| 53 | +原文链接: |
| 54 | +> http://stackoverflow.com/questions/604424/lookup-enum-by-string-value# |
0 commit comments