开发者

How to validate object serialization mechanism?

开发者 https://www.devze.com 2023-01-20 11:03 出处:网络
I\'m trying to validate that my custom Java object is serialized/de-serialized properly, and I can use this serialization mechanism with files, streams, etc. This is the test I created. Is it a correc

I'm trying to validate that my custom Java object is serialized/de-serialized properly, and I can use this serialization mechanism with files, streams, etc. This is the test I created. Is it a correct approach?

public class SerializableTest {
  @Test public void shouldSerialize() throws Exception {
    Foo foo = new Foo(123);

    // serialize it to a s开发者_Go百科tring
    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);
  }
}

What is wrong here?


Replace

String written = out.toString();

with

byte[] written = out.toByteArray();

You can't store random binary data as String. String is for text.


You are attempting to decode binary data to text and then encode back to binary. Always a bad idea.

You should also flush decorator output streams.


Nothing, as long as Foo has a proper equals implementation.

I would not pass it through the String transformation as this is evil as the other also remarked already.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号