Junaid S.
Junaid S.

Reputation: 2642

Clone Serializable Object - JAVA

I am learning how to clone serializable object. When I see the code I got confused that why we need to first serialize the object and then deserialize it ? Is it due to we want to get an Object (or any other reason) ? Then why we just not return the object or serialize object ?

public static Object clone(Serializable object) {
   return deserialize(serialize(object));
}

Upvotes: 2

Views: 7346

Answers (2)

Ashraf Purno
Ashraf Purno

Reputation: 1065

If the object itself was returned it will not be a clone of the object it will just be the same object so object can not be returned.

And the serialize can not be returned because the return type of clone() is Object and the return type of serialize() is byte[].

So in a nutshell the clone() method serializes the object into byte array by calling serialize(object) and then converts that byte array into a object by calling deserialize() with it. It results in a new Object with the same properties as the object.

Upvotes: 1

Junaid S.
Junaid S.

Reputation: 2642

Source

The (simple) clone() method of Object performs a shallow copy of an object. This means that primitive fields are copied, but objects within the cloned object are not copied. Rather, the references within the new object point to the objects referenced by the original object. This can sometimes lead to unexpected results. Sometimes a deep copy of an object is needed. In a deep copy, rather than references in the new object pointing to the same objects as the original class, the references point to new objects (whose values have been copied over).

That's why for deep cloning we first serialize (to copy primitive and non-primitive type objects) and then deserialize (to get and return object from bytes) the object so that we get every thing within the object not just primitive type.

Upvotes: 4

Related Questions