BlackCat
BlackCat

Reputation: 521

Serializing/Deserializing a subclass object in a method in Java

I want a save/load function in my class. I created a private subclass where I store every data that I want to save.

public class MyClass {

    private class Progress implements Serializable {
        private static final long serialVersionUID = 1L;    
        boolean val1 = true;
        int val2 = 0;
        ArrayList<String> list = new ArrayList<String>();
    }

    private Progress progress = new Progress();    

    public void loadProgress() {
        progress = null;
        try
        {
            FileInputStream fileIn = new FileInputStream("./tmp/progress.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            progress = (Progress) in.readObject();
            in.close();
            fileIn.close();
        }catch(IOException i)
        {
            i.printStackTrace();
            return;
        }catch(ClassNotFoundException c)
        {
            System.out.println("Progress class not found");
            c.printStackTrace();
            return;
        }
    }

    public void saveProgress() {
        try
        {
            File f = new File("./tmp/progress.ser");
            f.getParentFile().mkdirs();
            FileOutputStream outputstream = new FileOutputStream(f);
            ObjectOutputStream out = new ObjectOutputStream(outputstream);
            out.writeObject(progress);
            out.close();
            outputstream.close();
        }catch(IOException i) {
            i.printStackTrace();
        }
    }

}

But when I want to try this code, it gives me java.io.NotSerializableException exception in the saveProgress() method, and because of this, the loadProgress() method is not working too. How can I serialize this class?

Upvotes: 0

Views: 78

Answers (2)

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27476

Outer class also needs to be Serializable, because each inner class has an implicit reference to the outer class.

So to solve this you need to mark MyClass as Serializable or make Progress a static class. Static classes don't have reference to the outer class.

Upvotes: 1

Dici
Dici

Reputation: 25950

When you try serializing an instance of an inner class, the outer instance will also be serialized. In your case, MyClass is not serializable so it won't work. There are two possible workarounds:

  • make Progress a static nested class
  • make MyClass serializable

I would argue in favor of the first approach whenever it's possible since it serializes less data and therefore has better performance and space efficiency.

Upvotes: 1

Related Questions