Reputation: 1359
I am writing a game in java. Now i want to add a functionality to save the whole state of this game, for debugging purposes, and i want to write this by myself, without any libraries. A few possible ways to do this came to my mind, but i do'nt know which one I should choose - so I hope you can help me with this decision.
I could create a GameData - Class, save all the data I need in an Object of this class, and save it with an ObjectOutputStream. My thoughts about this solution: First of all, almost every class i have has to implement Serializbale. Is'nt this a bit ugly code? Furthermore, this GameData object should be passed through all Constructors and Objects, or every data should be set to public, to save the data there. And everytime I change the game, the GameData class and every peace of code that handles with it had to be changed.
I could traverse recursively through all objects with reflection, until i reach primitive types or strings, and save this data in a tree.. recunstruct it again with reflection.. but.. is this possible or do I forget some problems about that?
What do you think about that? Do you have other ideas?
Upvotes: 1
Views: 117
Reputation: 1889
There are a few problems to consider:
Your Object-Graph may have cycles, you somehow have to avoid serialising objects twice. The problem is then during reconstruction (load) that you need to reassign objects, even if they have not been loaded yet. You also need object identifiers to do that.
Another problem is that you may have references to classes that you didn't write yourself and that do no have Serializable
or Externalizable
implemented. You may have to replace these with own classes.
Yet another problem is to consider what happens if you change your data model. How will you be able to read old save games?
If your object graph is small and has no cycles, then option 2) is probably best. Otherwise I would consider using an open source database. You could for example use a relational databases with an O/R mapping layer (essentially making them look like object databases).
I actually wrote my own solution once, it is an actual object-databases (no mapping layer required) called ZooDB (www.zoodb.org). It runs embedded, i.e. no need to start a database server process or such. It's not quite finished yet, but should be good enough for what you require.
Upvotes: 1