この質問の回答に続いて:How can I initialise a static Map?私のプロジェクトで静的なマップを作成しようとしています。コードスニペットの下
:静的マップの初期化:null値が返される
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
を印刷します。
なぜですか?
いいえ、ありません。しかし、それはコンパイルされていないので、あなたの本当のコードではありません。 –
なぜこのコードをコンパイルできないのですか? – PenguinEngineer
MyMethodにセミコロンがないためです。問題を再現した完全な最小例を投稿してください。私はこのコードを取って修正し、MyMethodを呼び出すメインメソッドを追加すると、(私が予想したように)エラーを再現することができません。 –