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:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…