任何人都可以在下面的示例中解释序列化问题。我有两个相同的(等于返回真)映射 - 一个以标准方式初始化,第二个用双括号初始化。第二个不能序列化(抛出 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()
实用类:
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();
}
}
Cats萌萌
慕莱坞森
相关分类