开发者

XML serialization of references

I am writing a game which has a set of rules which should be loaded or saved from/to an XML file.

I have a UnitType class which can serialize and deserialize itself. I also have a Faction class which can load/save to XML. And I have a Rules class which contains

UnitType[] unitTypes;
Faction[] factions

When loading the rules, I first load all unit types objects and store their references into unitTypes Then I load Factions and store references to them into factions;

However, Faction class also has a member array UnitType[] accessibleUnitTypes, which shows which unit types this faction can build, and I need to load it, too.

Here comes the problem: since a reference is just an address, serializing it makes no sense (and also is impossible in Java), so I need to create a special field long ID inside the UnitType class and a special Manager class which has a method getUnitTypeByID(long ID). From now on, each time I create a UnitType object, I need to register it within the Manager (Manager has a HashMap<Long, UnitType> which maps IDs to the objects).

Now comes the problem that in java I can't explicitly delete objects. I can unregister the object from the Manager inside the finalize() method but since the reference to the object is still in the Manager, finalize() will never be called.

This makes me write another method onDeleting() inside UnitType, which should be called like delete in C++ each time the object is no longer needed. The onDeleting() method would then tell Manager to delete the referen开发者_如何学JAVAce to the object.

In the example above I mentioned only one class needing onDeleting() method, but say, I have a whole heirarchy of classes, and all of them need to serialize and deserialize themselves to XML.

I end up with the necessity to add onDeleting() method to any such class, and make sure that inside this method any memeber variables run their onDeleting() and so on. This now looks much like C++ where you'd call delete on pointers. This is probably not the Java way to do this. Is there any alternative?


It actually depends on how you do the XML<->Java mapping. If you use JAXB, you can use @XmlID / @XmlIDRef. If you roll your own, look into IdentityHashMap, and just generate back-references.


You should use one of the many XML serialization libraries rather than trying to solve all those problems all over again for yourself, and believe me you haven't found them all yet. Java.beans.XMLEncoder, XML Beans, JAXB, ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜