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) { = id;

    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( : != null) return false;

        return true;

    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:

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

        // serialize
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(out);

        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

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


  1. Replies
    1. Great Article android based projects

      Java Training in Chennai Project Center in Chennai Java Training in Chennai projects for cse The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

  2. 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

  3. Exciting online games with us best casinos online come in and win right now.