本文主要是介绍实现对象的克隆,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
实现对象的克隆有两种方式:
1)实现Clonable接口并重写Object类的clone()方法
2)实现Serializable接口,通过对象的序列化和反序列化,可以实行真正的深度克隆
package zqd.demo;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;public class MyUtil {private MyUtil(){}public static <T> T clone(T obj) throws Exception{ByteArrayOutputStream bout = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bout);oos.writeObject(obj);ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());ObjectInputStream oin = new ObjectInputStream(bin);T t = (T) oin.readObject();return t;}
}
Person:
package zqd.demo;import java.io.Serializable;public class Person implements Serializable {private static final long serialVersionUID = -6437218094443289723L;private String name;private int age;private Car car;public Person(String name, int age, Car car) {super();this.name = name;this.age = age;this.car = car;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Car getCar() {return car;}public void setCar(Car car) {this.car = car;}@Overridepublic String toString() {return "Person [name=" + name + ", age=" + age + ", car=" + car + "]";}}
Car:
package zqd.demo;import java.io.Serializable;public class Car implements Serializable {/*** */private static final long serialVersionUID = 3078573796509129909L;private String brand;private int maxSpeed;public Car(String brand, int maxSpeed) {super();this.brand = brand;this.maxSpeed = maxSpeed;}public String getBrand() {return brand;}public void setBrand(String brand) {this.brand = brand;}public int getMaxSpeed() {return maxSpeed;}public void setMaxSpeed(int maxSpeed) {this.maxSpeed = maxSpeed;}public static long getSerialversionuid() {return serialVersionUID;}@Overridepublic String toString() {return "Car [brand=" + brand + ", maxSpeed=" + maxSpeed + "]";}}
Test:
package zqd.thread;import zqd.demo.Car;
import zqd.demo.MyUtil;
import zqd.demo.Person;public class Task {public static void main(String[] args) {try {Person p1 = new Person("Hao LUO", 33, new Car("Benz", 300));Person p2 = MyUtil.clone(p1); // 深度克隆p2.getCar().setBrand("BYD");// 修改克隆的Person对象p2关联的汽车对象的品牌属性// 原来的Person对象p1关联的汽车不会受到任何影响// 因为在克隆Person对象时其关联的汽车对象也被克隆了System.out.println(p1);System.out.println(p2);} catch (Exception e) {e.printStackTrace();}}
}
输出:
Person [name=Hao LUO, age=33, car=Car [brand=Benz, maxSpeed=300]]
Person [name=Hao LUO, age=33, car=Car [brand=BYD, maxSpeed=300]]
这篇关于实现对象的克隆的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!