展开全部
先创建两个类,一个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();
}
}
}