我有以下类(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()));
    }
}

当我尝试调用getImageSignature()时,我收到一个NotSerializableException-为什么?所有成员都是可序列化的,为什么我会收到该错误?

最佳答案

每个ImageSignature实例都有一个对MyClass封闭实例的隐式引用,并且MyClass不可序列化。

使MyClass可序列化,或将ImageSignature声明为静态:

private static class ImageSignature implements Serializable {

09-28 01:08