简体   繁体   中英

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.

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; you can't serialize I/O connections like that.

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.

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.

So, you have to do as minimum 2 things:

1) Firm class also has to implement Serializable interface

2) mark Scanner field as transient

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM