为什么我的类不可序列化?

2024-01-02

我有以下课程:

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, and MyClass不可序列化。

要么让MyClass可序列化,或声明ImageSignature static:

private static class ImageSignature implements Serializable {
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么我的类不可序列化? 的相关文章

随机推荐