• 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();
     }
    }
  • 相关阅读:
    Django自带的用户认证auth模块
    Django logging模块
    python之MRO和垃圾回收机制
    Django内置form表单和ajax制作注册页面
    自定义登录验证的中间件
    中间件控制访问评率
    多表查询
    单表查询
    同一服务器部署多个tomcat时的端口号修改详情
    反射获取类中的属性和set属性
  • 原文地址:https://www.cnblogs.com/fu-yun/p/4552248.html
Copyright © 2020-2023  润新知