[英]Not Serializable Java
I can't figure out why is my class not serializable. 我不知道为什么我的课不能序列化。 As you can see below in my code my class implements Serializable interface.
正如您在下面的代码中看到的那样,我的类实现了Serializable接口。
public class Firm {
PrintWriter out = new PrintWriter(System.out, true);
Scanner sc = new Scanner(System.in);
Set<Worker> workers = new HashSet<>();
boolean saveToFile(){
String fileName = "text.txt";
ObjectOutputStream file;
boolean save = false;
try{
file = new ObjectOutputStream(new FileOutputStream(fileName));
file.writeObject(workers);
file.close();
save = true;
}catch(IOException e){
e.printStackTrace();
}
return save;
}
}
import java.io.Serializable;
public abstract class Worker implements Serializable {//Code
Any ideas how to fix it? 任何想法如何解决?
The problem is that the PrintWriter
and the Scanner
are not serializable; 问题是
PrintWriter
和Scanner
无法序列化; you can't serialize I/O connections like that. 您不能像这样序列化I / O连接。
Move those to wherever you're using them, if you need them at all, as local variables. 如果需要它们,请将它们作为局部变量移动到使用它们的任何位置。 Don't store them in the class.
不要将它们存储在课程中。
You should be assured that all fields in Worker
class also has type which implements Serializable
interface. 您应确保
Worker
类中的所有字段也具有实现Serializable
接口的类型。
According to your class names and stacktrace fragment from your commentary, it is most probably you have field with type Firm
inside Worker
class which is not serializable due to its structure. 根据您的类名和注释中的stacktrace片段,很可能您在
Worker
类中具有类型为Firm
字段,由于其结构,该字段不可序列化。
So, you have to do as minimum 2 things: 因此,您至少要做两件事:
1) Firm
class also has to implement Serializable
interface 1)
Firm
类还必须实现Serializable
接口
2) mark Scanner
field as transient
2)将
Scanner
字段标记为transient
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.