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?
If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java. io. Serializable, then it is serializable; otherwise, it's not.
You can determine whether an object is serializable at run time by retrieving the value of the IsSerializable property of a Type object that represents that object's type.
It'll throw a NotSerializableException when you try to Serialize it. To avoid that, make that field a transient field.
If a super class implements Serializable, then its sub classes do automatically. When an instance of a serializable class is deserialized, the constructor doesn't run. If a super class doesn't implement Serializable, then when a subclass object is deserialized, the super class constructor will run.
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.
utility methods based on skaffman's answer:
private static <T extends Serializable> byte[] pickle(T obj) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.close(); return baos.toByteArray(); } private static <T extends Serializable> T unpickle(byte[] b, Class<T> cl) throws IOException, ClassNotFoundException { ByteArrayInputStream bais = new ByteArrayInputStream(b); ObjectInputStream ois = new ObjectInputStream(bais); Object o = ois.readObject(); return cl.cast(o); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With