English 中文(简体)
如何验证对象序列化机制?
原标题:How to validate object serialization mechanism?
  • 时间:2010-10-13 16:47:33
  •  标签:
  • java

我正在尝试验证我的自定义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();

不能将随机二进制数据存储为字符串。字符串用于文本。

问题回答

您正试图将二进制数据解码为文本,然后再编码回二进制。总是个坏主意。

您还应该刷新decorator输出流。

什么都没有,只要Foo有一个适当的equals实现。

我不会让它通过String转换,因为这是邪恶的,正如另一个已经说过的那样。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签