次のコードのうち、非推奨とされる箇所があれば指摘してください。
try {
ResourceBundle bundle = ResourceBundle.getBundle("MyResource", Locale.US);
Properties props = new Properties();
bundle.keySet().stream()
.forEach(key -> props.put(key, bundle.getString(key)));
System.out.println(props.getProperty("code"));
} catch(MissingResourceException e) {
System.out.println("リソースが見つかりません" + e.getMessage());
}
MyResource_en_US
code=hundred
解答
非推奨のコード: put
理由: putはHashSetで宣言されたメソッドで、String型以外のエントリも挿入できてしまうため。
代替案: Object setProperty(String key, String value)
メソッドの使用。
出力:
hundred
PropertiesはHashtableを継承するので、Propertiesオブジェクトに対してputメソッドおよびputAllメソッドを適用できます。 しかし、これらのメソッドを使用することは推奨されません。これらのメソッドを使うと、呼出し側はキーまたは値がStringsではないエントリを挿入できるからです。 setPropertyメソッドを代わりに使用してください。