Can anybody explain serialization problems in example like below. I have two the same (equals return true) map - one is initialized in standard way and second one initialized with double braces. Second one can't be serialized (throwed NotSerializableException).
Map<String, Object> m = new HashMap<String, Object>(){
private static final long serialVersionUID = 1L;
{
put("test", "String");
}};
Map<String, Object> m2 = new HashMap<String, Object>();
m2.put("test", "String");
Assert.assertEquals(m, m2); // true
Assert.assertTrue(m.equals(m2)); // true
Assert.assertEquals(Utils.deserialize(Utils.serialize(m2)), m2); // ok
Assert.assertEquals(Utils.deserialize(Utils.serialize(m)), m); // java.io.NotSerializableException on serialize()
Utils class:
public class Utils {
static public Object deserialize(byte[] b) throws IOException, ClassNotFoundException {
ObjectInputStream ins = null;
try {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
ins = new ObjectInputStream(bais);
return ins.readObject();
} finally {
if(ins != null) {
ins.close();
}
}
}
static public byte[] serialize(Object o) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.flush();
oos.close();
bos.close();
return bos.toByteArray();
}
}