For various reasons I have a custom serialization where I am dumping some fairly simple objects to a data file. There are maybe 5-10 classes, and the object graphs that result are acyclic and pretty simple (each serialized object has 1 or 2 references to another that are serialized). For example:
class Foo
{
final private long id;
public Foo(long id, /* other stuff */) { ... }
}
class Bar
{
final private long id;
final private Foo foo;
public Bar(long id, Foo foo, /* other stuff */) { ... }
}
class Baz
{
final private long id;
final private List<Bar> barList;
public Baz(long id, List<Bar> barList, /* other stuff */) { ... }
}
The id field is just for the serialization, so that when I am serializing to a file, I can write objects by keeping a record of which IDs have been serialized so far, then for each object checking whether its child objects have been serialized and writing the ones that haven't, finally writing the object itself by writing its data fields and the IDs corresponding to its child objects.
What's puzzling me is how to assign id's. I thought about it, and it seems like there are three cases for assigning an ID:
dynamically-created objects -- id is assigned from a counter that increments
reading objects from disk -- id is assigned from the number stored in the disk file
singleton objects -- object is created prior to any dynamically-created object, to represent a singleton object that is always present.
How can I handle these properly? I feel like I'm reinventing the wheel and there must be a well-established technique for handling all the cases.