简体   繁体   English

Java可序列化的HashMap到ByteArray用于创建Blob

[英]Java serializable HashMap to ByteArray for creating a blob

When I tried it, I get this message error: 尝试时,出现此消息错误:

java.io.NotSerializableException: java.io.NotSerializableException:

  private HashMap<String, XlsData> myMap= new HashMap<String, XlsData>();

        ByteArrayOutputStream bObj = new ByteArrayOutputStream();
            ObjectOutputStream out;
                try {
                out = new ObjectOutputStream(bObj);
                if(myMap != null){
                out.writeObject(myMap);
                out.close();
                bObj.close();
                byte[] byteOut = bObj.toByteArray();
              }
              } catch (IOException e) {
                e.printStackTrace();
            }

    public class XlsData implements Serializable {

            private String dataA;
            private String dataB;

            public String getDataA() {
                return dataA;
            }
            public void setDataA(String dataA) {
                this.dataA= dataA;
            }
            public String getDataB() {
                return dataB;
            }
            public void setDataB(String dataB) {
                this.dataB= dataB;
            }
}

What it's necessary to works fine? 工作正常需要什么? As it's possible see my inner class implements a serializabe class too. 有可能看到我的内部类也实现了serializabe类。

Your XlsData class needs to be a static inner class: 您的XlsData类需要是一个静态内部类:

public static class XlsData implements Serializable {

Because it is not static, it behaves like a non-static field: it can only exist as part of an instance of the outer class. 因为它不是静态的,所以它的行为就像一个非静态字段:它只能作为外部类实例的一部分存在。 When you serialize an instance of a non-static inner class, you are also serializing the enclosing outer class object, which I'm guessing is not serializable (or one or more of its fields is not serializable). 当序列化一个非静态内部类的实例时,您还将序列化封闭的外部类对象,我猜这是不可序列化的(或其一个或多个字段不可序列化)。

Most likely, simply one of the elements of you're map isn't serializable. 最有可能的是,您所映射的元素之一只是不可序列化的。 Or an element of the map holds a member that is neither serializable nor transient. 或者,映射的元素包含既不可序列化也不瞬态的成员。 Just look through the map and you should find the answer. 只需翻阅地图,即可找到答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM