注意:我打算将其作为一个问题发布,但我在SSCCE中重现问题的尝试使我找到了下面发布的解决方案。
我的代码中有一个类,其中private
非static
字段在 static
final
字段之前初始化 。我无法在以下SSCCE中重现该问题:
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
)字段吗?
答案 0 :(得分: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
修饰符),使其在{{1}的所有其他成员之前初始化(例如,使其成为硬编码的MyClass
路径)。