首页 > 代码库 > java的clone
java的clone
java的浅克隆,十分简单。但是只会克隆基本的数据类型,当涉及到引用类型时就不好用了。
public class Employee implements Cloneable { private String name; private String gender; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Employee clone() throws CloneNotSupportedException { return (Employee) super.clone(); } }
实现深克隆的话有两种方法,一种就是引用的类也是实现了clone方法的。另一种是通过序列化来进行克隆。
第一种方法,需要将引用的类需要每个都clone。
public class Employee implements Cloneable { private String name; private String gender; private Date birthday; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Employee clone() throws CloneNotSupportedException { Employee cloned = (Employee) super.clone(); cloned.birthday = (Date) birthday.clone(); return cloned; } }
第二种方法就不需要这么做了。
package clone; import java.io.*; import java.sql.Date; public class Employee implements Serializable { private static final long serialVersionUID = 4435396040456359326L; private String name; private String gender; private Date birthday; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Object deepClone(Object obj) throws IOException, ClassNotFoundException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); return ois.readObject(); } }
java的clone
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。