I want to make a copy of an object, then after some logic, re-assign the original object the value of the copy.
example:
User userCopy = //make a copy foreach(...) { user.Age = 1; user.ID = -1; UserDao.Update(user) user = userCopy; }
I don't want a copy by reference, it has to be a copy by value.
The above is just a sample, not how I really want to use it but I need to learn how to copy by value.
assign() method is used to copy all enumerable values from a source object to the target object. Example: const obj = {a:1,b:2,c:3}; const clone = Object. assign({},obj); console.
To create a copy of an existing object in the vault, right-click the object of your choice and select Make Copy from the context menu. This command creates an entirely new object using the metadata and contents of the source object.
Objects are assigned and copied by reference. In other words, a variable stores not the “object value”, but a “reference” (address in memory) for the value. So copying such a variable or passing it as a function argument copies that reference, not the object itself.
Here are the few techniques I've heard of:
Use clone()
if the class implements Cloneable
. This API is a bit flawed in java and I never quite understood why clone
is not defined in the interface, but in Object
. Still, it might work.
Create a clone manually. If there is a constructor that accepts all parameters, it might be simple, e.g new User( user.ID, user.Age, ... )
. You might even want a constructor that takes a User: new User( anotherUser ).
Implement something to copy from/to a user. Instead of using a constructor, the class may have a method copy( User )
. You can then first snapshot the object backupUser.copy( user )
and then restore it user.copy( backupUser )
. You might have a variant with methods named backup
/restore
/snapshot
.
Use the state pattern.
Use serialization. If your object is a graph, it might be easier to serialize/deserialize it to get a clone.
That all depends on the use case. Go for the simplest.
EDIT
I also recommend to have a look at these questions:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With