如何强制实例化静态字段
我对以下代码的输出感到非常惊讶:
Country class
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);
}
}
}
Main method
System.out.println(Country.getCountry("Spain"));
Output
空
是否有任何干净的方法可以强制加载扩展 Country 的类,以便国家地图包含所有 Country 实例?
I was quite surprised of the output of the following code:
Country class
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);
}
}
}
Main method
System.out.println(Country.getCountry("Spain"));
Output
null
Is there any clean way of forcing the class that extend Country to be loaded so the countries map contains all the Country instances?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,使用静态初始化块:
Yes, use static initializer block:
在您调用
Country.getCountry("Spain")
时,您的类EuropeCountry
尚未加载。正确的解决方案是这只是一个例子...还有其他方法可以实现相同的目的(另请参阅彼得的回答)
Your class
EuropeCountry
was not loaded at the time you calledCountry.getCountry("Spain")
. The correct solution would beThis is just an example... There are other ways to achieve the same (see also Peter's answer)
您需要加载
EuropeCountry
类。在致电国家之前提及它就足够了。You need to load the
EuropeCountry
class. Any reference to it before calling Country will enough.