[英]NullPointerException when de-serializing a saved object ?
我使用命令行參數輸入指令。 我通過了包含有關如何運行類的信息的文本文件所在的位置。 在一種情況下,程序必須像發生錯誤一樣動作,並且需要關閉。 我能夠做到這一點。 最后該對象也被serlized。 現在,我必須使用相同的ser文件來重新啟動程序,並從與上次使用restore類關閉的位置相同的位置啟動它。 由於某些奇怪的原因,我得到了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
;
}
此時的異常只能是因為fileNameNew
為null
。 而且不會扔在那里。 它必須在構造函數鏈或它調用的某些方法中拋出。
在嘗試對任何內容進行反序列化之前 ,問題就已經發生了,並且(實際上)與反序列化過程無關。
實際上, fileNameNew
為null
的原因是您正在嘗試在實例初始化程序塊中進行操作。 (壞主意...)該塊在Restore
構造函數主體之前執行,並且此時, fileNameNew
字段仍將處於其默認的初始化狀態。
解決方案是將實例初始化程序塊中的代碼放在構造函數中,以便在this.fileNameNew = fileName;
之后執行this.fileNameNew = fileName;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.