我正在尝试验证我的自定义 Java 对象是否已正确序列化/反序列化,并且我可以对文件、流等使用此序列化机制。这是我创建的测试。这是正确的做法吗?
public class SerializableTest {
@Test public void shouldSerialize() throws Exception {
Foo foo = new Foo(123);
// serialize it to a string
ByteArrayOutputStream out = new ByteArrayOutputStream();
new ObjectOutputStream(out).writeObject(foo);
String written = out.toString();
// read it back
ByteArrayInputStream in = new ByteArrayInputStream(written.getBytes());
Foo foo2 = (Foo)(new ObjectInputStream(in).readObject());
// check that two objects are identical
assertEquals(foo, foo2);
}
}
这里出了什么问题?
最佳答案
替换
String written = out.toString();
与
byte[] written = out.toByteArray();
您不能将随机二进制数据存储为字符串。字符串用于文本。
关于java - 如何验证对象序列化机制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3926000/