Java Deep Copy without Serialization
I have been writing a card game for Android, and I am desperately stuck on how to save my game state. To briefly explain my program, I have a Spri开发者_开发百科te class for displaying my cards which contains a bitmap image, a point for the position, and a bounding rectangle. I inherit this class to make a card class which has two bitmaps which are switched depending on whether the card is face up or down, and enumerations for storing suit and rank. These card objects are place in CardStack objects which contain and additional position, and an arraylist of cards. The game model consists of various CardStacks, and the rules for move cards between stacks. The game works great as is.
Now I am trying to figure out how to save my game state. I would like to serialize my entire game object and save it to a file. However, there are numerous objects (bitmap, point, rectangle, color, etc) that are not serializable. In C#, I know you can use a MemoryStream and just copy the whole object, but I can't find a similar method in Java that does not require everything to be serializable. Is there anything similar in Java? Any better way I could structure my game model object? Any advice would be greatly appreciated. Thanks!
abstract the gui into business objects and make the gui objects encapsulate these business objects
this way a card doesn't need to know what bitmap it needs to be displayed (or even that it gets displayed at all)
those business objects are what you want to serialize and the gui can be rebuild from the deserialized objects
You can always write your own customized serialization methods within Java's serialization framework. See Serializable.
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void writeObject(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
private void readObjectNoData() throws ObjectStreamException;
You are correct that Java's default implementation will fail if your object contains non-serializable objects, but you can define how to serialize them in methods above.
Also: on Android, you may want to use Parcelable
which is Android's version of serialization.
Take a look at protocol buffers (protobuf)
精彩评论