【发布时间】:2012-03-30 09:09:51
【问题描述】:
在 Java 中调用类的静态方法会触发静态初始化块执行吗?
根据经验,我会说不。我有这样的事情:
public class Country {
static {
init();
List<Country> countries = DataSource.read(...); // get from a DAO
addCountries(countries);
}
private static Map<String, Country> allCountries = null;
private static void init() {
allCountries = new HashMap<String, Country>();
}
private static void addCountries(List<Country> countries) {
for (Country country : countries) {
if ((country.getISO() != null) && (country.getISO().length() > 0)) {
allCountries.put(country.getISO(), country);
}
}
}
public static Country findByISO(String cc) {
return allCountries.get(cc);
}
}
在使用该类的代码中,我执行以下操作:
Country country = Country.findByISO("RO");
问题是我得到一个NullPointerException,因为地图(allCountries)没有初始化。如果我在 static 块中设置断点,我可以看到映射被正确填充,但就好像静态方法不知道正在执行的初始化程序。
谁能解释这种行为?
更新:我在代码中添加了更多细节。仍然不是 1:1(其中有几张地图和更多逻辑),但我已经明确查看了 allCountries 的声明/引用,它们如上所列。
你可以看到完整的初始化代码here。
更新 #2:我尝试尽可能简化代码并即时将其写下来。实际代码在初始化器之后有静态变量声明。正如乔恩在下面的答案中指出的那样,这导致它重置了参考。
我修改了帖子中的代码以反映这一点,因此对于找到问题的人来说更清楚。很抱歉给大家带来了困惑。我只是想让每个人的生活更轻松:)。
感谢您的回答!
【问题讨论】:
-
你能显示初始化地图的代码吗?
-
顺便说一句,您在示例中缺少 findByISO() 方法的返回类型。
标签: java static initialization