对象的克隆:
对象的克隆分为浅克隆和深克隆。
对象浅克隆注意的细节:
- 如果一个对象需要调用clone的方法克隆,那么该对象所属的类必须要实现Cloneable接口。
- Cloneable接口只不过是一个标识接口而已,没有任何方法。
- 对象的浅克隆就是克隆一个对象的时候,如果被克隆的对象中维护了另外一个类的对象,这时候只是克隆另外一个对象的地址,而没有把另外一个对象也克隆一份。
- 对象的浅克隆也不会调用到构造方法的。
浅克隆案例:
class Address implements Serializable{
String city;
public Address(String city){
this.city = city;
}
}
public class Person implements Cloneable,Serializable {
int id;
String name;
Address address;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public Person(int id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
System.out.println("=======构造方法调用了===");
}
@Override
public String toString() {
return "编号:"+ this.id+" 姓名:"+ this.name+" 地址:"+ address.city;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Demo1 {
public static void main(String[] args) throws Exception {
Address address = new Address("广州");
Person p1 = new Person(110,"狗娃",address);
//Person p2=p1;//这种方式属于对象地址的引用
Person p2 = (Person) p1.clone(); //clone() 克隆了一个对象。
p2.name = "狗剩";
p2.address.city ="长沙";
System.out.println("p1:"+p1);
System.out.println("p2:"+ p2);
}
}
对象的深克隆:
对象的深克隆就是利用对象的输入输出流把对象先写到文件上,然后再读取对象的信息这个过程就称作为对象的深克隆。
ObjectInputStream
ObjectOutputStream
深克隆案例:
public class Demo2 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Address address = new Address("广州");
Person p1 = new Person(110,"狗娃",address);
writeObj(p1);
Person p2 =readObj();
p2.address.city = "长沙";
System.out.println("p1:"+ p1);
System.out.println("p2:"+ p2);
}
//再从文件中读取对象的信息
public static Person readObj() throws ClassNotFoundException, IOException{
FileInputStream fileInputStream = new FileInputStream("F:\\obj.txt");
//创建对象的输入流对象
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
return (Person) objectInputStream.readObject();
}
//先要把对象写到文件上。
public static void writeObj(Person p) throws IOException{
//建立一个文件 的输出流对象
FileOutputStream fileOutputStream = new FileOutputStream("F:\\obj.txt");
//建立对象的输出流
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
//把对象写出
objectOutputStream.writeObject(p);
//关闭资源
objectOutputStream.close();
}
}