-2

注:質問として投稿するつもりでしたが、SSCCE で問題を再現しようとした結果、以下に投稿された解決策にたどり着きました。

コードにクラスがあり、フィールドのprivateに非staticフィールドが初期化されています。次の SSCCE では問題を再現できませんでした。static final

public class MyClass {

    private static final File myDefaultPath = 
                new File(System.getProperty("user.home"), "DefaultPath");

    private JFileChooser myFileChooser = new JFileChooser() {

        // File chooser initialization block:
        {
            myDefaultPath.mkdirs(); 
                // In my code, the above line throws:
                // java.lang.ExceptionInInitializerError
                // Caused by: java.lang.NullPointerException
                //    at init.order.MyClass$1.<init>(MyClass.java:18)
                //    at init.order.MyClass.<init>(MyClass.java:14)
                //    at init.order.MyClass.<clinit>(MyClass.java:9)
            setCurrentDirectory(myDefaultPath);
        }
    };

    public static void main (String[] args) {
        new MyClass().myFileChooser.showDialog(null, "Choose");
    }
}

何らかの理由で、File myDefaultPathが の前に初期化されていませんJFileChooser myFileChooser

static(特にstatic final) フィールドを最初に初期化すべきではありませんか?

4

1 に答える 1

1

私のコードでは、私のクラスstaticはそれ自体 (シングルトン) のインスタンスを格納します。これらのフィールドは、シングルトンの初期化後にテキストで来る他のフィールドの前に開始されます。static

public class MyClass {
    private static MyClass c = 
            new MyClass();

    private static final File myDefaultPath = 
                new File(System.getProperty("user.home"), "DefaultPath");

    private JFileChooser myFileChooser = new JFileChooser() {

        // File chooser initialization block:
        {
            myDefaultPath.mkdirs(); // This code *will* throw an exception!
            setCurrentDirectory(myDefaultPath);
        }
    };

    public static void main (String[] args) {
        c.myFileChooser.showDialog(null, "Choose");
    }
}

考えられる解決策は次のとおりです。

  • myDefaultPathシングルトンの初期化の前に初期化を 移動します。
  • myDefaultPathコンパイル時の定数になるように変更して (staticおよび修飾子を保持してfinal)、他のすべてのメンバーの前に初期化するようにしますMyClass(たとえば、ハードコードされたStringパスにします)。

  • 于 2013-09-16T08:25:35.927 に答える