简体   繁体   English

HashMap 不可序列化

[英]HashMap not Serializable

HashMap with Serializable key/value is supposed to be Serializable .带有Serializable键/值的HashMap应该是Serializable

But it's not working for me.但这对我不起作用。 Tried some other IO streams.尝试了一些其他的 IO 流。 None works.没有工作。

Any suggestion?有什么建议吗?

Test code测试代码

public class SimpleSerializationTest {
    @Test
    public void testHashMap() throws Exception {
        HashMap<String, String> hmap = new HashMap<String, String>() {{
            put(new String("key"), new String("value"));
        }};

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        out = new ObjectOutputStream(bos);
        out.writeObject(hmap);
        byte[] yourBytes = bos.toByteArray();
        if (out != null) {
            out.close();
        }
        bos.close();

        ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
        ObjectInput in = null;
        in = new ObjectInputStream(bis);
        Object o = in.readObject();
        bis.close();
        if (in != null) {
            in.close();
        }

        assertEquals(hmap, o);
    }
}

Stack trace堆栈跟踪

java.io.NotSerializableException: SimpleSerializationTest
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    at SimpleSerializationTest.testHashMap(SimpleSerializationTest.java:18)

Process finished with exit code 0

The exception message tells you exactly what the problem is: you are trying to serialize an instance of class SimpleSerializationTest , and that class is not serializable.异常消息准确地告诉您问题是什么:您正在尝试序列化SimpleSerializationTest类的实例,而该类不可序列化。

Why?为什么? Well, you have created an anonymous inner class of SimpleSerializationTest , one that extends HashMap , and you are trying to serialize an instance of that class.好吧,您已经创建了SimpleSerializationTest的匿名内部类,它扩展了HashMap ,并且您正在尝试序列化该类的实例。 Inner classes always have references to the relevant instance of their outer class, and by default, serialization will try to traverse those.内部类始终引用其外部类的相关实例,默认情况下,序列化将尝试遍历这些实例。

I observe that you use a double-brace {{ ... }} syntax as if you think it has some sort of special significance.我观察到您使用双括号{{ ... }}语法,好像您认为它具有某种特殊意义。 It is important to understand that it is actually two separate constructs.重要的是要了解它实际上是两个独立的结构。 The outer pair of braces appearing immediately after a constructor invocation mark the boundaries of the inner class definition.在构造函数调用之后立即出现的外部大括号标记了内部类定义的边界。 The inner pair bound an instance initializer block, such as you can use in any class body (though they are unusual in contexts other than anonymous inner classes).内部对绑定了一个实例初始化块,例如您可以在任何类主体中使用(尽管它们在匿名内部类以外的上下文中是不常见的)。 Ordinarily, you would also include one or more method implementations / overrides inside the outer pair, either before or after the initializer block.通常,您还会在外部对中包含一个或多个方法实现/覆盖,无论是在初始化程序块之前还是之后。

Try this instead:试试这个:

    public void testHashMap() throws Exception {
        Map<String, String> hmap = new HashMap<String, String>();

        hmap.put(new String("key"), "value");

        // ...
    }

A working version of your code :您的代码的工作版本:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;

import org.junit.Test;

import junit.framework.Assert;

public class SimpleSerializationTest implements Serializable{
    @Test
public void testHashMap() throws Exception {
    HashMap<String, String> hmap = new HashMap<String, String>() {{
        put(new String("key"), new String("value"));
    }};

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;
    out = new ObjectOutputStream(bos);
    out.writeObject(hmap);
    byte[] yourBytes = bos.toByteArray();
    if (out != null) {
        out.close();
    }
    bos.close();

    ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
    ObjectInput in = null;
        in = new ObjectInputStream(bis);
        HashMap<String, String> o = (HashMap<String, String>) in.readObject();
        bis.close();
        if (in != null) {
            in.close();
        }

        Assert.assertEquals(hmap, o);
    }
}

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

相关问题 可序列化的对象到Hashmap的Arraylist - Serializable object to Arraylist of Hashmap 为什么并发HashMap可序列化 - Why Concurrent HashMap is Serializable HashMap和Serializable问题 - HashMap and issue with Serializable 使用不可序列化的对象序列化哈希图 - Serialize hashmap with non-serializable objects Java可序列化的HashMap到ByteArray用于创建Blob - Java serializable HashMap to ByteArray for creating a blob 如果我在使用Hashmap时没有实现Serializable会发生什么 - What happens if I don't implement Serializable when using Hashmap 尽管类是可序列化的,为什么HashMap的哈希表被标记为临时表 - Why is the hash table of HashMap marked as transient although the class is serializable 宁静的服务端点为ResponseEntity &lt;HashMap生成XML响应 <String, Serializable> &gt; - Restful service endpoint to produce XML response for ResponseEntity< HashMap<String, Serializable>> 为什么系统会自动将我的 LinkedHashMap 转换为 HashMap,同时将它作为可序列化的 Intent 传递? - Why is the system automatically converting my LinkedHashMap to HashMap while passing it in an Intent as a Serializable? 无法在android putExtra方法中将java.util.hashmap $ values强制转换为java.io.serializable - java.util.hashmap$values cannot be cast to java.io.serializable in android putExtra method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM