I have an object of type Record which implements Serializable. In my task, I have to split it into two objects of the same type, where one has all original fields except for one field, and the other only the field excluded at the previous step. Here is what I did:
Record firstPart = SerializationUtils.clone(record); Record secondPart = new Record(); firstPart.setUid(null); secondPart.setUid(record.getUid()); Now, I was told that I shouldn't have cloned record. Perhaps they mean it's too expensive if the record is big enough. I tried to figure out how to avoid cloning, but can't get it. What could be the solution?
#cloneis protected, and is not typically intended to be called outside of the controlling class (Record). There's a litany of reasons to avoid its usage, but that doesn't mean it isn't always possible. A "copy constructor" in this case would be more explicit and clear to someone reading the code. If it's alreadyCloneablethen go wild, but otherwise definitely don't introduceCloneableif it isn't there. For context,Object#clonedoes nothing if the object doesn't implementCloneable.SerializationUtils#clonewould callObject#clone.