how to test in Java that a class implements Serializable correctly (not just is an instance of Serializable)

The easy way is to check that the object is an instance of java.io.Serializable or java.io.Externalizable, but that doesn’t really prove that the object really is serializable.

The only way to be sure is to try it for real. The simplest test is something like:

new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(myObject);

and check it doesn’t throw an exception.

Apache Commons Lang provides a rather more brief version:

SerializationUtils.serialize(myObject);

and again, check for the exception.

You can be more rigourous still, and check that it deserializes back into something equal to the original:

Serializable original = ...
Serializable copy = SerializationUtils.clone(original);
assertEquals(original, copy);

and so on.

Leave a Comment