java 深层复制_Java中如何通过序列化进行深层复制

展开全部

先创建两个类,一个e5a48de588b63231313335323631343130323136353331333365653864学生类和一个课程类(两个类都要实现Serializable接口才能被序列化),学生类有一个属性为课程。import java.io.Serializable;

/**

* 课程类

*/

public class Course implements Serializable {

private String name;

public Course(String name) {

this.name = name;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}import java.io.Serializable;

/**

* 学生类

*/

public class Student implements Serializable {

// 学号

private int id;

// 姓名

private String name;

// 课程

private Course course;

public Student() {

}

public Student(int id, String name, Course course) {

this.id = id;

this.name = name;

this.course = course;

}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public Course getCourse() {

return course;

}

public void setCourse(Course course) {

this.course = course;

}

}

对象复制:import java.io.*;

public class ObjectCopy {

public static void main(String[] args) {

Course course = new Course("java程序设计");

Student stu = new Student(1, "jack", course);

System.out.println("原对象hashcode:" + stu.hashCode());

try {

// 序列化

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ObjectOutputStream oos = new ObjectOutputStream(baos);

oos.writeObject(stu);

// 反序列化

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

ObjectInputStream ois = new ObjectInputStream(bais);

// 复制后的对象

Student copy = (Student) ois.readObject();

System.out.println("新对象hashcode:" + copy.hashCode());

System.out.println(copy.getCourse().getName());

} catch (IOException e) {

e.printStackTrace();

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值