字节数组流实现深克隆
- 浅克隆,只是实现对地址的引用。如Object的clone方法
- 深克隆,将宿主完全克隆一份,包括引用类型。
public class P4 {
@Test
public void testClone() throws IOException, ClassNotFoundException {
Student s1=new Student(2,"小河");
Student newStu = getNewObject(s1);
System.out.println(newStu);
newStu.setName("小菜");
System.out.println("newStu:"+newStu);
System.out.println("s1:"+s1);
}
public Student getNewObject(Student s) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream=new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(s);
byte[] bytes = byteArrayOutputStream.toByteArray();
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream=new ObjectInputStream(byteArrayInputStream);
return (Student) objectInputStream.readObject();
}
}
class Student implements Serializable{
private Integer id;
private String name;
public Student() {
}
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}