为什么我的课程无法序列化? [英] Why is my class not serializable?

查看:100
本文介绍了为什么我的课程无法序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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 -为什么?所有成员都是可序列化的,为什么我会收到该错误?

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

推荐答案

ImageSignature的每个实例 MyClass 的封闭实例具有隐式引用,而 MyClass 不可序列化。

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

要么使 MyClass 可序列化,要么声明 ImageSignature 静态:

Either make MyClass serializable, or declare ImageSignature static:

private static class ImageSignature implements Serializable {

这篇关于为什么我的课程无法序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆