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.Serializableorjava.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:
and check it doesn’t throw an exception.
Apache Commons Lang provides a rather more brief version:
and again, check for the exception.
You can be more rigourous still, and check that it deserializes back into something equal to the original:
and so on.