I keep getting java.io.NotSerializableException: java.io.ObjectOutputStream

房东的猫 提交于 2019-12-05 20:54:45

Only primitives and classes that implement Serializable interface can be serialized. ObjectOutputStream doesn't implement this interface.

Quick solution: use the ObjectOutputStream in the narrowest possible scope, declare it in the method where it's being used, not as a field in the class. Do similar with other utility classes like 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();
    }
}

Another solution may be just marking these fields as transient so they won't be serialized/deserialized:

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

    protected transient ObjectOutputStream accData;

     transient Scanner input = new Scanner(System.in);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!