我一直得到java.io.NotSerializableException:java.io.ObjectOutputStream

时间:2015-04-12 17:35:47

标签: java exception serializable

这是我一直在尝试的代码

import java.util.Scanner;
import java.io.*;

abstract class Account implements Serializable {
    protected String accountHolderName;
    protected long balance;

    protected ObjectOutputStream accData;

    Scanner input = new Scanner(System.in);
}

class Savings extends Account implements Serializable {

    Savings() throws IOException {
        System.out.print("enter your name: ");
        accountHolderName = input.nextLine();
        System.out.print("\n");
        System.out.print("enter your balance: ");
        balance = input.nextLong();
        accData = new ObjectOutputStream(new FileOutputStream(accountHolderName + ".bin"));
        accData.writeObject(this);
        accData.close();
    }
}

class Banking implements Serializable {
    public static void main(String args[]) throws IOException {
        Scanner input = new Scanner(System.in);
        Savings savobj = new Savings();
    }
}

这是我得到的例外

  

线程中的异常" main" java.io.NotSerializableException:   java.io.ObjectOutputStream中               at java.io.ObjectOutputStream.writeObject0(Unknown Source)               at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)           at java.io.ObjectOutputStream.writeSerialData(Unknown Source)           at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)           at java.io.ObjectOutputStream.writeObject0(Unknown Source)           at java.io.ObjectOutputStream.writeObject(Unknown Source)           在储蓄。(Banking.java:22)           在Banking.main(Banking.java:30)

我也尝试使用savobj.accData.writeObj(savobj)中的main(,但我仍然得到相同的异常。我该怎么办?

1 个答案:

答案 0 :(得分:5)

只能实现Serializable接口的基元和类的序列化。 ObjectOutputStream没有实现此界面。

快速解决方案:在尽可能最窄的范围内使用ObjectOutputStream,在使用它的方法中声明它,而不是在类中的字段。与其他实用程序类(如Scanner

类似
abstract class Account implements Serializable {
    protected String accountHolderName;
    protected long balance;

    //protected ObjectOutputStream accData;

    //Scanner input = new Scanner(System.in);
}

class Savings extends Account implements Serializable {

    Savings() throws IOException {
        Scanner input = new Scanner(System.in);
        System.out.print("enter your name: ");
        accountHolderName = input.nextLine();
        System.out.print("\n");
        System.out.print("enter your balance: ");
        balance = input.nextLong();
        ObjectOutputStream accData = new ObjectOutputStream(new FileOutputStream(accountHolderName + ".bin"));
        accData.writeObject(this);
        accData.close();
    }
}

另一个解决方案可能只是将这些字段标记为transient,因此无法对其进行序列化/反序列化:

abstract class Account implements Serializable {
    protected String accountHolderName;
    protected long balance;

    protected transient ObjectOutputStream accData;

     transient Scanner input = new Scanner(System.in);
}