gpt4 book ai didi

java - 反序列化保存的对象时出现 NullPointerException 吗?

转载 作者:行者123 更新时间:2023-12-01 12:07:17 28 4
gpt4 key购买 nike

我使用命令行参数输入指令。我传递了包含有关如何运行该类的信息的文本文件所在的位置。在一种情况下,程序必须表现得好像出现错误并且需要关闭。我有能力做到这一点。该对象最终也被序列化。现在我必须使用相同的 ser 文件来重新启动程序,并从上次使用恢复类关闭的位置启动它。由于某些奇怪的原因,我收到了 nullpinterException 。我已经标记了出现该错误的位置。

public static void main(String[] args) throws Exception {

try {

String option = args[0];
String filename = args[1];


if (!(option.equals("-f")) && !(option.equals("-d"))) {
System.out.println("Invalid option");
printUsage();
}

System.out.println(filename);
GreenhouseControls gc = new GreenhouseControls();

if (option.equals("-f")) {
gc.addEvent(gc.new Restart(0, filename));
try {
FileOutputStream fileOut = new FileOutputStream("/Users/Arsalan Khan/Google Drive/cosc/TME/src/dumpout.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(gc);
out.close();
} catch (IOException i) {
i.printStackTrace();
}
}
gc.run();

// serialization try catch


// the instance where the error occored is also passed to
if (option.equals("-d")) {

// GreenhouseControls.main(GreenhouseControls.java:567)
Restore re = new Restore(filename);


}

}

catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid number of parameters");
printUsage();
e.printStackTrace();
}

}

public class Restore {
String fileNameNew;

public Restore(String fileName) {

this.fileNameNew = fileName;

}

// print the state of the save to the console
{// deserilize dump.out
try {
// here at Restore.<init>(Restore.java:17)
FileInputStream fileIn = new FileInputStream(fileNameNew);
ObjectInputStream in = new ObjectInputStream(fileIn);

// it has to be cast to GreenhouseControls since everything saved in
// a file is retrieved as an object
GreenhouseControls readGreen = (GreenhouseControls) in.readObject();
in.close();
System.out.println(readGreen);
// since we are trying to fix the error in gc we will pass its
// instance and use fixable to fix it
readGreen.getFixable((Integer) readGreen.errorCode);
} catch (IOException | ClassNotFoundException i) {
i.printStackTrace();
}
}

// restart from where it left the program
// run fix window and power on to fix problems

;

}

最佳答案

此时出现异常只能是因为 fileNameNewnull。而且它不会被在那里。它必须被抛出到构造函数链中,或者它调用的某个方法中。

问题发生在您尝试反序列化任何内容之前,并且(实际上)与反序列化过程无关。

事实上,fileNameNewnull 的原因是您试图在实例初始值设定项 block 中执行操作。 (坏主意......)该 block 在 Restore 构造函数主体之前执行,此时,fileNameNew 字段仍将处于默认初始化状态。

解决方案是将实例初始化 block 中的代码放入构造函数内部,以便它在 this.fileNameNew = fileName;

之后执行

关于java - 反序列化保存的对象时出现 NullPointerException 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494222/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com