Why is my class not serializable?

F.P picture F.P · Feb 23, 2012 · Viewed 19.3k times · Source

I have the following class:

import java.awt.Color;
import java.util.Vector;

public class MyClass {

    private ImageSignature imageSignature;

    private class ImageSignature implements Serializable {
        private static final long serialVersionUID = -6552319171850636836L;
        private Vector<Color> colors = new Vector<Color>();

        public void addColor(Color color) {
            colors.add(color);
        }

        public Vector<Color> getColors() {
            return colors;
        }
    }

    // Will be called after imageSignature was set, obviously
    public String getImageSignature() {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(imageSignature);
        oos.close();
        return String(Base64Coder.encode(baos.toByteArray()));
    }
}

When I try to call getImageSignature(), I get an NotSerializableException - Why is that? All members are serializable, so why do I get that error?

Answer

NPE picture NPE · Feb 23, 2012

Every instance of ImageSignature has an implicit reference to the enclosing instance of MyClass, and MyClass is not serializable.

Either make MyClass serializable, or declare ImageSignature static:

private static class ImageSignature implements Serializable {