在我的前端 html 中,当未选择任何国家/地区时,将保存国家/地区 0。
在我的后端,在我的java代码中,我希望有一个0来表示没有选择国家。
我在 0 ("");
上遇到语法错误
因此,当我获得国家/地区代码 0
时,枚举代码不会在 System.out.println(Country.valueOf("0").getCountry()); 上失败。
请多多指教,谢谢。
public static void main (String []args) {
System.out.println(Country.valueOf("SG").getCountry());
}
public static enum Country {
MY ("Malaysia"),
SG ("Singapore"),
ID ("Indonesia"),
0 (""); //for null blank
private final String country;
private Country(String levelCode) {
this.country = levelCode;
}
public String getCountry() {
return this.country;
}
}
最佳答案
虽然其他答案包含有用的建议,但我想解释一下您的错误原因以及 Java 枚举的限制。
语法错误的原因是在Java(和大多数其他编程语言)中,枚举常量是一个标识符,并且标识符必须以字母(或下划线,当然不推荐)开头。 0
不是字母。
这反过来也意味着无论您做什么,Country.valueOf("0")
都永远不会工作(人们可能会想象覆盖枚举中的方法,但事实并非如此)可能)。
两个建议:
使用另一个名称,以字母开头。
NULL_BLANK (""); //for null blank
使用
null
表示没有国家/地区。
对于不同的名称,我认为是 COUNTRY_0
、BLANK
或 ZERO
。无论您使用上面的第 1 项还是第 2 项,您都必须编写自己的查找方法,如 Joakim Danielson’s answer 中所示。 ,例如。
编辑:一个可能更好的解决方案可能是一个枚举,其中构造函数接受键和国家/地区名称作为参数:
public static enum Country {
MALAYSIA ("MY", "Malaysia"),
SINGAPORE ("SG", "Singapore"),
INDONESIA ("ID", "Indonesia"),
NULL_BLANK ("0", ""); //for null blank
private static final Map<String, Country> BY_KEY
= Arrays.stream(values()).collect(Collectors.toMap(c -> c.key, c -> c));
public static Country of(String key) {
return BY_KEY.get(key);
}
private final String key;
private final String country;
private Country(String key, String name) {
this.key = key;
this.country = name;
}
public String getCountry() {
return this.country;
}
}
一个优点是它允许使用更好的枚举常量名称,MALAYSIA
而不是 MY
等。我提供了 of
查找方法。例如使用:
System.out.println("MY -> \"" + Country.of("MY").getCountry() + "\"");
System.out.println("0 -> \"" + Country.of("0").getCountry() + "\"");
输出:
MY -> "Malaysia" 0 -> ""
关于java - 带数字键的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57122100/