Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deep copy an arbitrary object in GWT?

Tags:

java

gwt

I have an arbitrary object tagged as Serializable. It has various mutable child objects representing monetary amounts, collections etc. I want to be able to clone this object so if the user modifies it and then reverts their action, I can just replace the clone with a fresh clone.

That implies I need a deep copy because I don't want the users changes to child objects (e.g. adding / inserting items from the collection) appearing on the original.

The objects don't implement Cloneable and as they're autogenerated I can't add such a method either.

Short of painfully handwriting a deep clone is there anyway to accomplish the same in GWT? If this were Java I could consider serializing the object to a byte array stream and deserializing a fresh copy.

I can't do that in GWT. Potentially I could harness RPC because the object is sent to a servlet later. I just don't know if that is easy to do.

Anyone know a simple way I can do a deep copy?

like image 975
locka Avatar asked Mar 01 '11 17:03

locka


People also ask

How do you make an exact copy of an object?

Clone() method in Java. Object cloning refers to the creation of an exact copy of an object. It creates a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object. In Java, there is no operator to create a copy of an object.

Does the clone method do a shallow or a deep copy?

clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.


1 Answers

If you have a chance to add an interface or annotation to your domain classes, you can use gwt-ent for reflection, and you can easily write your own deep copy semantic by means of reflection. I have used this technique to improve gwt serialization performance in dev mode.

As another solution, you can use gwt default serialization mechanism for deep copy, but unfotunately I dont have any clue how you could accomplish this goal..

like image 58
Gursel Koca Avatar answered Sep 20 '22 08:09

Gursel Koca