Saturday, 27 November 2010

Java Serialization Part 1

I wondered what my first post would be, and here it is. Java Serialization!

If I have a plain Java object that is serializable:

public class Pojo implements Serializable {

    private String id;

    public Pojo(String id) {
        this.id = id;
    }
 

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Pojo pojo = (Pojo) o;

        if (id != null ? !id.equals(pojo.id) : pojo.id != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }
}


...then how can I prove that it is serializable? Turns out that it's not that difficult at all. A quick Google, and I find this page which had some unit test code on it which I could modify:

    @Test
    public void shouldSerializeAndDeserialize() throws Exception {
        // construct test object
        Pojo original = new Pojo("id");

        // serialize
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(out);
        oos.writeObject(original);
        oos.close();

        //deserialize
        byte[] pickled = out.toByteArray();
        InputStream in = new ByteArrayInputStream(pickled);
        ObjectInputStream ois = new ObjectInputStream(in);
        Object o = ois.readObject();
        Pojo copy = (Pojo) o;

        // test the result
        assertTrue(original.equals(copy));
    }

In the next post, I'll discuss controlling instances of this simple object.

2 comments:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai

    ReplyDelete