zoukankan      html  css  js  c++  java
  • java的clone

    做项目时有时可能会遇到需要克隆对象的时候,因为有时候对象是直接从别的类get到的,那样引用的是一个对象,修改的话会将原先的对象也修改了。

    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编码专题】JAVA字符编码系列一:Unicode,GBK,GB2312,UTF-8概念基础
    读取Webpage表中的内容
    各种排序算法的分析及java实现
    运行一个Hadoop Job所需要指定的属性
    Hbase常见异常
    Gora官方文档之二:Gora对Map-Reduce的支持
    Linux 系统挂载数据盘
    Gora快速入门
    Gora官方范例
    在Eclipse中运行Nutch2.3
  • 原文地址:https://www.cnblogs.com/fu-yun/p/4552248.html
Copyright © 2011-2022 走看看