2

私の目的は、クラスにプライベート静的オブジェクトを設定し、アプリケーションに必要なProperties他のオブジェクトを作成するときにデフォルトとして機能することです。Properties現在の実装は次のようになります。

public class MyClass {
    private static Properties DEFAULT_PROPERTIES = new Properties();

    static {
        try {
           DEFAULT_PROPERTIES.load(
               MyClass.class.getResourceAsStream("myclass.properties"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
 }

それを見ると、それは機能しますが、それは正しく感じられません。

どうしますか?

4

3 に答える 3

6

基本的に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;
}
于 2010-01-08T12:09:39.517 に答える
5

一般的なRuntimeExceptionの代わりに、ExceptionInInitializerErrorをスローします。これは、この目的を正確に表すためのものです。APIドキュメントから:「静的初期化子で予期しない例外が発生したことを示すシグナル。」

于 2010-01-08T11:52:57.640 に答える
0

私には受け入れられるようです。静的イニシャライザーにロードします。クラスが参照されている場合にのみ呼び出され、1回だけ呼び出されます。それはいいですね。私がする唯一のことはそれを作ることfinalです。

まあ、例外は別として。私はどういうわけかそれを避けようとします(私はあなたがそれらのタイプのイニシャライザーの例外を避けるべきであると私の心の後ろに持っています、しかし私はそれについて間違っているかもしれません)。

于 2010-01-08T11:37:46.860 に答える