I am implementing a class to be Serializable (so it's a value object for use w/ RMI). But I need to test it. Is there a way to do this easily?
clarification: I'm implementing the class, so it's trivial to stick Serializable in the class definition. I need to manually serialize/deserialize it to see if it works.
I found this C# question, is there a similar answer for Java?
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.