【发布时间】:2017-04-01 15:22:49
【问题描述】:
按照这个问题的答案:How can I initialise a static Map? 我正在尝试在我的项目中创建一个静态地图。
下面一段代码 sn -p:
public class MyClass {
public static final Map<String, String> dataMap;
static {
Map<String, String> tempMap = new HashMap<String, String>();
try {
// Getting a string value from a file, e.g. String data
String data = "data";
tempMap.put("firstData", data);
}
catch(Exception e) {}
dataMap = Collections.unmodifiableMap(tempMap);
//DEBUG (I test it and it correctly prints "data")
System.out.println(dataMap.get("firstData"));
}
}
然后我在另一个类中调用地图,像这样:
public class AnotherClass {
@Before
public void MyMethod() {
System.out.println(MyClass.dataMap.get("firstData"));
}
@Test
public void testMethod() {}
}
现在它打印null,而不是值“data”。
为什么?
【问题讨论】:
-
不,它没有。但这不是你真正的代码,因为它甚至不能编译。
-
为什么不能编译这段代码?
-
因为 MyMethod 中缺少分号。发布一个完整的最小示例来重现该问题。如果我使用这段代码并修复它,并添加一个调用 MyMethod 的主方法,我将无法重现错误(如我所料)。
-
好的问题刚刚编辑
-
无法复制。你可能有另一个名为 MyClass 的类,或者忘记重新编译,或者类似的东西。
标签: java collections static hashmap initialization