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();
     }
    }
  • 相关阅读:
    数据库连接字符串
    搭建消息队列
    Linux---江湖
    Bundle压缩JS和CSS
    DDD分层架构之仓储
    UI控件库
    图解Http协议 url长度限制
    JAVA jdbc(数据库连接池)学习笔记(转)
    领域驱动设计(DDD)部分核心概念的个人理解(转)
    怎样的中奖算法能让人信服(转)
  • 原文地址:https://www.cnblogs.com/fu-yun/p/4552248.html
Copyright © 2011-2022 走看看