寻找实现String转换的现代方法,以替代外观不好的if-else或switch结构:
if ("UK".equals(country))
name = "United Kingdom";
if ("GE".equals(country))
name = "Germany";
if ("FR".equals(country))
name = "France";
if ("IT".equals(country))
name = "Italy";
[...]
或
switch (country) {
case "UK": name = "United Kingdom"; break;
case "GE": name = "Germany" break;
case "FR": name = "France"; break;
case "IT": name = "Italy" break;
[...]
答案 0 :(得分:13)
您可能需要一个enum
。
public enum Country {
UK("United Kingdom"),
GE("Germany"), // sure this isn't DE?
FR("France");
// and so on
private String countryName;
private Country(String n) { countryName = n; }
public String getCountryName() { return countryName; }
}
现在您可以
Country c = Country.valueOf(countryString); // throws exception when unknown
name = c.getCountryName();
答案 1 :(得分:1)
我认为最干净的方法是继承,并在您的代码中引入一些简单的数据结构来表示此类信息。扩展代码时,这将阻止您的开关升级。让我们有一个抽象基类Country
,它提供了一些属性,例如'Name'。名称永远不会改变,并且是特定于类型的。因此,我们定义了一个类UK
,该类继承自Country
。现在,您可以使用多态并遍历Country
类型的所有国家/地区,并通过访问(只读)属性'Name'来检索其名称,而无需进行任何开关或类型强制转换。添加新国家/地区后,您无需再碰这种声明。
List<String> countries = new ArrayList<>();
countries.Add(new UK());
countries.Add(new Italy());
for (Country country : countries)
{
String countryName = country.getName();
}
答案 2 :(得分:0)
另一种可能性是使用HashMap:
private final Map<String, String> countries = new HashMap<String, String>() {
{
put("UK", "United Kingdom");
put("GE", "Germany");
put("FR", "France");
put("IT", "Italy");
[...]
}
};
name = countries.get(county);
答案 3 :(得分:0)
您可以简单地使用java.util.Map。
创建静态国家/地区变量。
private static final String UK = "UK";
private static final String GE = "GE";
private static final String FR = "FR";
private static final String IT = "IT";
private static final Map<String, String> COUNTRIES;
static {
final Map<String, String> countries = new HashMap<>();
countries.put(UK, "United Kingdom");
countries.put(GE, "Germany");
countries.put(FR, "France");
countries.put(IT, "Italy");
COUNTRIES = Collections.unmodifiableMap(countries);
}
然后可以使用java.util.Map中的“ get”属性来获取国家/地区名称
System.out.println(COUNTRIES.get(UK));
System.out.println(COUNTRIES.get(GE));
System.out.println(COUNTRIES.get(FR));
System.out.println(COUNTRIES.get(IT));