There is an amusing use for the serialization mechanism: It gives you an easy way to clone an object, provided the class is serializable. Simply serialize it to an output stream and then read it back in. The result is a new object that is a deep copy of the existing object. You don’t have to write the object to a file—you can use a
ByteArrayOutputStream to save the data into a byte array.
As Listing 1.4 shows, to get
clone for free, simply extend the
SerialCloneable class, and you are done.
You should be aware that this method, although clever, will usually be much slower than a clone method that explicitly constructs a new object and copies or clones the data fields.