基本的に2つの方法があります。最初の方法は、示したように静的ブロックを使用することです(ただし、のExceptionInInitializerError
代わりにを使用しますRuntimeException
)。2番目の方法は、宣言時にすぐに呼び出す静的メソッドを使用することです。
private static Properties DEFAULT_PROPERTIES = getDefaultProperties();
private static Properties getDefaultProperties() {
Properties properties = new Properties();
try {
properties.load(MyClass.class.getResourceAsStream("myclass.properties"));
} catch (IOException e) {
throw new ConfigurationException("Cannot load properties file", e);
}
return properties;
}
は、ConfigurationException
を拡張するカスタムクラスにすることができますRuntimeException
。
私は個人的にブロックを好みます。なぜなら、その人生で一度だけstatic
実行されるメソッドを持つことは意味がないからです。ただし、ファイル名を取得してグローバルに再利用できるようにメソッドをリファクタリングする場合は、それがより望ましいでしょう。
private static Properties DEFAULT_PROPERTIES = SomeUtil.getProperties("myclass.properties");
// Put this in a SomeUtil class.
public static Properties getProperties(String filename) {
Properties properties = new Properties();
try {
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename));
} catch (IOException e) {
throw new ConfigurationException("Cannot load " + filename, e);
}
return properties;
}