package com.io;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class CopyObject {
public static void main(String[] args) throws IOException,ClassNotFoundException,CloneNotSupportedException{
Student stu=new Student(1,"admin","admin");
//light copy
Student lightCopy=(Student) stu.clone();
//deep copy
/*将对象写入到内存流中*/
ByteArrayOutputStream bos=new ByteArrayOutputStream();
ObjectOutputStream oos=new ObjectOutputStream(bos);
oos.writeObject(stu);
/*从内存中将对象通过流的方式读出来*/
ByteArrayInputStream bis=new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois=new ObjectInputStream(bis);
Object deepCopy=ois.readObject();
System.out.println("deepCopy:"+deepCopy);
System.out.println("lightCopy"+lightCopy);
}
}
class Student implements Serializable,Cloneable
{
private static final long serialVersionUID = 1L;
private Integer id;
private String userName;
private String password;
public Student(Integer id, String userName, String password) {
super();
this.id = id;
this.userName = userName;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Object clone() throws CloneNotSupportedException
{
return super.clone();
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "Student[id:"+id+", userName:"+userName+", password:"+password+"]";
}
}
Io-浅拷贝和深拷贝
最新推荐文章于 2025-01-11 12:09:17 发布