Here are the few techniques I’ve heard of:
-
Use
clone()
if the class implementsCloneable
. This API is a bit flawed in java and I never quite understood whyclone
is not defined in the interface, but inObject
. 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 objectbackupUser.copy( user )
and then restore ituser.copy( backupUser )
. You might have a variant with methods namedbackup
/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:
- Clone() vs. Copy constructor
- How to properly override clone method