java如何将String转换为enum

绝地灬酷狼 2023-10-02 16:30 28阅读 0赞

问题

假设定义了如下的enum(枚举):

  1. public enum Blah {
  2. A, B, C, D
  3. }

已知枚举对应的String值,希望得到对应的枚举值。例如,已知”A”,希望得到对应的枚举——Blah.A,应该怎么做?
Enum.valueOf()是否能实现以上目的,如果是,那我如何使用?

答案

是的,Blah.valueOf(“A”) 将会得到 Blah.A

静态方法valueOf() 和 values() 不存在于源码中,而是在编译时创建,我们也可以在JavaDoc查看到它们,比如 Dialog.ModalityTyp 就中出现这两个方法。

其他答案

当文本和枚举值不同时,可以采用这种方式:

  1. public enum Blah {
  2. A("text1"),
  3. B("text2"),
  4. C("text3"),
  5. D("text4");
  6. private String text;
  7. Blah(String text) {
  8. this.text = text;
  9. }
  10. public String getText() {
  11. return this.text;
  12. }
  13. public static Blah fromString(String text) {
  14. for (Blah b : Blah.values()) {
  15. if (b.text.equalsIgnoreCase(text)) {
  16. return b;
  17. }
  18. }
  19. return null;
  20. }
  21. }

fromString方法中,throw new IllegalArgumentException(“No constant with text “ + text + “ found”) 会比直接返回null更优秀.

其他答案

我有一个挺赞的工具方法:

  1. /**
  2. * A common method for all enums since they can't have another base class
  3. * @param <T> Enum type
  4. * @param c enum type. All enums must be all caps.
  5. * @param string case insensitive
  6. * @return corresponding enum, or null
  7. */
  8. public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {
  9. if( c != null && string != null ) {
  10. try {
  11. return Enum.valueOf(c, string.trim().toUpperCase());
  12. } catch(IllegalArgumentException ex) {
  13. }
  14. }
  15. return null;
  16. }

你可以这么使用:

  1. public static MyEnum fromString(String name) {
  2. return getEnumFromString(MyEnum.class, name);
  3. }

发表评论

表情:
评论列表 (有 0 条评论,28人围观)

还没有评论,来说两句吧...

相关阅读