Java: when serializing an object, I get NotSerializableException from classes I'm not trying to serialize

StackOverflow https://stackoverflow.com/questions/21791872

Question

I have three packages inside src: model, view, and controller. view has a couple of JFrames, model has a couple of classes that deal with the logic of the program, and controller has one class containing instances of the JFrames from view, and only one object from model, called 'board'. I should mention that in model there is a class called Saver that only has a static method to load and a static method to save this object 'board'.

When I try to serialize the object 'board' (board and all of the classes in model are Serializable), I get in the stack trace NotSerializableException from all of the classes in view, and all of the inner classes in the controller class, when I am only trying to serialize 'board', which belongs to model, and all of board's variables are Serializable.

Here are the methods to save and load from the Saver class:

public class Saver {

public static void saveBoard(Board board) throws IOException{
    FileOutputStream fileOutputStream = new FileOutputStream("gosavefile.gsf");
    ObjectOutputStream obout = new ObjectOutputStream(fileOutputStream);

    obout.writeObject(board);

    fileOutputStream.close();
    obout.close();
}

public static Board loadBoard() throws IOException, ClassNotFoundException{
    FileInputStream fileInputStream = new FileInputStream("gosavefile.gsf");
    ObjectInputStream obin = new ObjectInputStream(fileInputStream);

    Board board = (Board) obin.readObject();

    fileInputStream.close();
    obin.close();

    return board;
}

}

And this is where I call the saveBoard() method from the controller class:

public void save(){
    try{
        Saver.saveBoard(board);
    } catch (IOException e) {
        new SaveErrorWindow(mainMenuWindow.getLanguageManager());
        e.printStackTrace();
    }
}

I have done it this way once before, with another program using the same exact scheme and it worked perfectly. So I really can't figure out why it is trying to serialize everything else when I'm only serializing 'board'.

If any other part of the code is needed, just ask.

Thank you in advance!

Was it helpful?

Solution

It's not enough that the classes implement java.io.Serializable. You also have to guarantee that all fields are serializable as well (either primitives or classes that implement Serializable), and so on. If any class has a non-serializable field which is not declared as transient, serialization will fail. Your stack trace should point which class caused the problem.

OTHER TIPS

In order to be serialized, an object must:

  • Implement Serializable
  • All non-transient and non-static fields must be primitive or serializable. Arrays are consider serializable, but its elements must be serializable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top