Cloning an Object in Java
I am trying to clone a DTO. I have taken a DTO Object as s开发者_如何学运维hown:
public class Employee implements Cloneable
{
String name;
String dept;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
}
But this line is giving me Error :
public class Test
{
public static void main(String args[]) {
Employee emp1 = new Employee();
emp1.setDept("10");
emp1.setName("Kiran");
Employee emp2 = (Employee) emp1.clone(); // This Line is giving error .
}
}
My query is that clone method is from Object
, so why can't we use it directly like we do the `toString Method?
You have to override Object.clone(), which is protected. See the java.lang.Cloneable and Object.clone() documentation.
More complete example here: How to implement Cloneable interface.
Unfortunately cloning in Java is broken. If you have an option, either try to define your own clone interface, one which actually has a clone
method or use copy constructors to create copies of object.
Actually, never mind. You need to override the clone method in your class since its protected in java.lang.Object. Don't forget to remove the CloneNotSupportedException in the method signature, so that you don't have to handle it everywhere in your code.
精彩评论