Tuesday, February 18, 2020

Java: Let's serialize with a map

Lets just use a map. So we have a timer like thing:

public class Time implements Serializable {

    private long duration;
    private long start;

    // crazy things

}

Now lets put everything in a map:

    private void writeObject(java.io.ObjectOutputStream out) throws ... {
        Map map = new HashMap<>();

        map.put("duration", duration);
        map.put("start", start);
        out.writeObject(map);
    }

Now lets get everything back from the map:

    private void readObject(java.io.ObjectInputStream in) throws ... {
        Map map = (java.util.Map) in.readObject();

        duration = (long) map.get("duration");
        start = (long) map.get("start");
    }

Lets also put this because we are handling the versioning:

    public static final long serialVersionUID = 1L;

However this is too much stuff to write, so lets make a script to write it for us: https://maanoo.com/testing/JavagenSerialMap.html

Now lets add a new thing to see how to handle versioning

    private TimeUnit unit;  // v.2

So we have to update the things: (our script that is)

    private void writeObject(java.io.ObjectOutputStream out) throws ... {
        Map map = new HashMap<>();

        map.put("duration", duration);
        map.put("start", start);
        map.put("unit", unit);
        out.writeObject(map);
    }

    private void readObject(java.io.ObjectInputStream in) throws ... {
        Map map = (Map) in.readObject();

        duration = (long) map.get("duration");
        start = (long) map.get("start");
        if (map.containsKey("unit")) {
            unit = (TimeUnit) map.get("unit");
        } else {
            // TODO unit
        }
    }

And we replace the TODO by setting the default value of the unit:

    unit = TimeUnit.Milliseconds

Also, if or when we are sure that there is none of the old version left, we can remove the check of the key and remove the setting of the default value.

Except the full control that this system provides, the actual data that are stored are serialized primitives and collections, making possible to be access and/or debug the saved data by external program.



done_