Why is my class not serializable?

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 NotSerializableException- Why? All members are serializable, so why am I getting this error?

+5
source share
3 answers

Each instance ImageSignaturehas an implicit reference to the enclosing instance MyClass, and is MyClassnot serializable.

Either make MyClassserializable or declare ImageSignaturestatic:

private static class ImageSignature implements Serializable {
+15
source

Check out the following information from the Java Serialization Spec :

Note. (.. , -), , . , , . , javac ( JavaTM-) - ; , serialVersionUID. , . , serialPersistentFields . , , , ( ), Externalizable. , , .

+1

To create a Serializable class, you must implement the Serlizable interface, which is a marker or tag interface that has no method, so your class object must seralize

private static class ImageSignature implements Serializable {// code }
+1
source

All Articles