Cloning is rarely a good idea in Java. Try other methods, such as copy constructors or Factory methods.
Wikipedia is a good article on why clone() has many flaws in Java.
Using copy constructors, create a constructor that takes an instance of the current class as a parameter, and copy all the fields in the local class:
public class Foo { private String bar; private String baz; public Foo(Foo other) { this.bar = other.bar; this.baz = other.baz; } }
Using Factory methods, create a method that takes your object as a parameter and returns an object containing the same values:
public Foo copyFoo(Foo other) { Foo foo = new Foo(); foo.setBar(other.getBar()); foo.setBaz(other.getBaz()); }
Vivien barousse
source share