繁体   English   中英

从单个字符解码Java枚举

[英]Decode Java enum from single char

我有

java.lang.Enum.valueOf(Enum.java:238)没有枚举常量[...]

当我尝试将单个char字符串解码为枚举时。

有什么问题,我该如何解决?

public class testEnum {

    public enum Colors {
        RED("R"), GREEN("G"), BLUE("B");
        private final String code;

        Colors(String code) {
            this.code = code;
        }

        public String getCode() {
            return code;
        }

    }

    public static void main(String args[]) throws Exception {
        Colors c = Colors.valueOf("R");
        System.out.println(c);
    }
}

在这种情况下,我希望对输出控制台使用RED

Colors.valueOf("R")是一个隐式声明的方法,也是Enum.valueOf(Colors.class, "R")的快捷方式。

Enum.valueOf状态的文档

@param name要返回的常量的名称

您的常数是REDGREENBLUE

您可能想通过其字段获取枚举实例。

有什么问题,我该如何解决?

Java无法知道您正在尝试传递code字段的值来进行查找。

要解决此问题,请指定完整名称:

Colors.valueOf("RED")

或构造一个Map<String, Colors>可以从中查找实例。

Map<String, Colors> map = new HashMap<>();
for (Colors colors : Colors.values()) {
  map.put(colors.code, colors);
}
// Assign to a field somewhere.

// Then, later:
Colors c = map.get("R");

从您调用的方法的文档中:

valueOf:
Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
Returns:
the enum constant with the specified name

对于您的情况,枚举“名称”将为“红色”,“绿色”或“蓝色”。 或者如果您想引用枚举,则为Colors.RED.name()

如果要查找与代码相对应的Colors枚举,则可以执行以下操作:

public class Sampler {
    public enum Colors {
        RED("R"), BLUE("B"), GREEN("G");

        private static final Map<String, Colors> COLORS_MAP;

        static {
            COLORS_MAP = new HashMap<>();
            for(Colors color : values()) {
                COLORS_MAP.put(color.code, color);
            }
        }

        private final String code;

        Colors(String code) {
            this.code = code;
        }

        public String getCode() {
            return code;
        }

        public static Colors fromCode(String code) {
            return COLORS_MAP.get(code);
        }
    }

    public static void main(String[] args) {
        Colors c = Colors.fromCode("R");
        System.out.println(c);
    }
}

我的决定

public enum Colors {
    RED("R"), GREEN("G"), BLUE("B");
    private final String code;

    Colors(String code) {
        this.code = code;
    }

    public String getCode() {
        return code;
    }

    public static Colors ofCode(String code){
        Colors[] values = Colors.values();
        for (Colors value : values) {
            if(value.code.equals(code)){
                return value;
            }

        }
        throw new IllegalArgumentException("Code not found"); 
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM