-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 myDefaultPathJFileChooser 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为编译时常量(并保留它的staticfinal修饰符)以使其在所有其他成员之前初始化MyClass(例如,使其成为硬编码String路径)。

  • 于 2013-09-16T08:25:35.927 回答