我对以下代码的输出感到非常惊讶:
国家级
public class Country {
private static Map<String, Country> countries = new HashMap<String, Country>();
private final String name;
@SuppressWarnings("LeakingThisInConstructor")
protected Country(String name) {
this.name = name;
register(this);
}
/** Get country by name */
public static Country getCountry(String name) {
return countries.get(name);
}
/** Register country into map */
public static void register(Country country) {
countries.put(country.name, country);
}
@Override
public String toString() {
return name;
}
/** Countries in Europe */
public static class EuropeCountry extends Country {
public static final EuropeCountry SPAIN = new EuropeCountry("Spain");
public static final EuropeCountry FRANCE = new EuropeCountry("France");
protected EuropeCountry(String name) {
super(name);
}
}
}
主要方法
System.out.println(Country.getCountry("Spain"));
输出
null
是否有任何干净的方法强制加载扩展 Country 的类,以便国家 map 包含所有 Country 实例?
最佳答案
是的,使用 static initializer block :
public class Country {
private static Map<String, Country> countries = new HashMap<String, Country>();
static {
countries.put("Spain", new EuroCountry("Spain"));
}
...
关于java - 如何强制实例化静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5963520/