我有以下代码尝试序列化/反序列化Throwable
public void test() throws IOException, ClassNotFoundException {
IllegalStateException exception = new IllegalStateException("Oooops!");
ByteBuffer seralized = serialize(exception);
String asString = new String(seralized.array(), Charset.forName("UTF-8"));
Throwable deserialized = deserialize(seralized);
// false
System.out.println(exception.equals(deserialized));
// true
System.out.println(exception.toString().equals(deserialized.toString()));
seralized = serialize(deserialized);
String toCompare = new String(seralized.array(), Charset.forName("UTF-8"));
// true
System.out.println(asString.equals(toCompare));
}
private Throwable deserialize(ByteBuffer seralized) throws IOException, ClassNotFoundException {
return (Throwable) new ObjectInputStream(new GZIPInputStream(
new ByteArrayInputStream(seralized.array()))).readObject();
}
private ByteBuffer serialize(Throwable exception) throws IOException {
ByteArrayOutputStream causeBytesOut = new ByteArrayOutputStream();
ObjectOutputStream causeOut = new ObjectOutputStream(
new GZIPOutputStream(causeBytesOut));
causeOut.writeObject(exception);
causeOut.close();
return ByteBuffer.wrap(causeBytesOut.toByteArray());
}
解释代码:我正在测试我的序列化/反序列化是否兼容。
第一个打印输出(错误)告诉我反序列化后得到的任何内容都与我序列化的内容不同。
第二个打印(真)告诉对象“有点”相似。
我试图深入每个对象,看看有什么区别,所以我再次序列化它并查看字节缓冲区的内容。根据最后一次打印(真),这看起来是相同的。
为什么初始对象和经过序列化/反序列化的对象不同,虽然看起来是一样的?