JAVAlang.ExceptionInInitializerError是在交换机中构造对象时创建的
在一个开关中,我创建了一个类配置单元的实例。在创建对象之后,它返回到我的开关并点击断点,然后出现错误
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
at Garden.fileReader(Garden.java:141)
at Garden.<init>(Garden.java:28)
at Garden.<clinit>(Garden.java:10)'
错误发生在运行switch语句之后,然后进入一个单独的类来构造对象,当返回并点击break时,错误弹出
public class Garden {
public static final Garden GARDEN = new Garden(); //line 10------------
public static void main(String[] args) {
int mainI = 0;
while (mainI != 100) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
GARDEN.anotherDay();
mainI++;
}
}
static HashMap<String, Hive> HiveMap = new HashMap<String, Hive>();
private Garden() {
fileReader(); //line 28 --------------------------
System.out.println("fileReader worked");
}
protected void fileReader() { // asks for file name for config file
//removed try catch code that uses Scanner to get input from console
// to select a file that is set to configFile
Scanner configScanner = new Scanner(configFile);
int k = 0;
while (configScanner.hasNextLine() == true) {
String inputLine = configScanner.nextLine();
//removed long if statment to set k
switch (k) {
case 1:
intFinder(k, inputLine);
Hive hive = new Hive(honeyInput, pollenInput, royalJellyInput);
HiveMap.put("hive" + hiveName, hive); line 141-------------
break; // it gets to this break then throws the error
// removed code
default:
break;
}
}
cmdReader.close();
configScanner.close();
}
配置单元的构造函数是
protected Hive(int honeyStart, int royalJellyStart, int pollenStart)
{
bees = new ArrayList<Bee>();
this.setHoney(honeyStart);
this.setRoyalJelly(royalJellyStart);
this.setPollen(pollenStart);
}
很抱歉发布了这么多代码,但我唯一知道的问题是,当代码在另一个类中运行时,configScanner会丢失数据,而事实并非如此,因此我不知道出现了什么问题。非常感谢您的帮助
# 1 楼答案
这是因为
Garden GARDEN
的初始值设定项运行时,HiveMap
尚未初始化。将初始化HiveMap
的行移到Garden GARDEN
前面的一行以解决此问题:这解决了问题的原因是静态初始值设定项按文本顺序运行。
Garden()
构造函数假定HiveMap
为非null,因为它试图将数据放入其中:# 2 楼答案
静态事物按顺序进行评估。在第10行,您试图创建一个
new Garden()
,它试图访问静态成员HiveMap
,但它尚未初始化。只需将new Garden()
移动到main
方法中