反序列化保存的对象时是否出现NullPointerException?

时间:2014-12-15 22:19:55

标签: java serialization nullpointerexception

我使用命令行参数输入指令。我传递了包含有关如何运行类的信息的文本文件所在的位置。在一个例子中,程序必须表现得像是有错误并且需要关闭。我能做到这一点。该对象最终也被清除了。现在我必须使用相同的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

;

}

1 个答案:

答案 0 :(得分:1)

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

问题发生在之前你试图反序列化任何事情,并且(实际上)与反序列化过程无关。

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

解决方案是将实例初始化程序块中的代码放在构造函数中,以便在this.fileNameNew = fileName;之后执行