Tuesday, December 23, 2008

Testing object serialization

Usually for this test, you just write the data onto a FileOutputStream. If no exception is thrown, the test passes. The example below is to test the serialization of EpHtmlEmail.
public void testIsSerializable() 
throws JaxenException, IOException {

try {
OutputStream fout = new FileOutputStream("testSerializable.ser");
ObjectOutputStream out = new ObjectOutputStream(fout);

EpHtmlEmail email = new EpHtmlEmail();
email.setTextMsg("Your email client does not support HTML messages");
email.setHostName("smtp.elasticpath.com");
email.setTest("testing");
email.setSmtpPort(2525);
......
out.writeObject(email);
out.flush();
out.close();

//deserialize
InputStream in = new FileInputStream("testSerializable.ser");
ObjectInputStream ois = new ObjectInputStream(in);
Object o = ois.readObject();
EpHtmlEmail epHtmlEmail = (EpHtmlEmail) o;

} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EmailException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


If the parent class does not implement Serialzable but the child class does, after serialization and de-serialization, what will happen?
Our "EpHtmlEmail" extends commons-email HtmlEmail and implements Serializable, while commons-email HemlEmail does not implement Serializable.
public class EpHtmlEmail extends HtmlEmail implements Serializable {
private String test;

public String getTest() {
return test;
}

public void setTest(String test) {
this.test = test;
}
}

After serialization and de-serialization, only property of "EpHtmlEmail" was de-serialized. All properties of parent class were gone. The properties of parent are the values after it is constructed. All primitive properties are restored to their default value if they are not set value in constructor.

No comments:

Post a Comment