gpt4 book ai didi

java - 我不断收到 java.io.NotSerializableException : java. io.ObjectOutputStream

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:44:42 25 4
gpt4 key购买 nike

这是我一直在尝试的代码

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();
}
}

这是我得到的异常

Exception in thread "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) at Savings.(Banking.java:22) at Banking.main(Banking.java:30)

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

最佳答案

只有实现Serializable 接口(interface)的原语和类才能被序列化。 ObjectOutputStream 没有实现这个接口(interface)。

快速解决方案:在尽可能窄的范围内使用 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);
}

关于java - 我不断收到 java.io.NotSerializableException : java. io.ObjectOutputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29592425/

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