Following the answers of this question: How can I initialise a static Map? I'm trying to create a static Map in my project.
Below a code snippet:
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"));
}
}
Then I call the map in another class, like this:
public class AnotherClass {
@Before
public void MyMethod() {
System.out.println(MyClass.dataMap.get("firstData"));
}
@Test
public void testMethod() {}
}
Now it prints null
, instead of the value "data".
Why?