public class CarCloneTest {
public static void main(String[] args) {
Brand brand = new Brand("BMW");
Car car = new Car(5, brand);
Car carClone;
// carClone = (Car) car.clone(); //(1)
// carClone = (Car) car.deepClone(); //(2)
carClone = CloneUtil.deepClone(car);
System.out.println("******************************************");
System.out.println("car "+car);
System.out.println("carClone "+carClone);
System.out.println("******************************************");
System.out.println("将car年限改为 7,品牌名称改为Banz");
brand.setName("Banz");
car.setYear(7);
System.out.println("******************************************");
System.out.println("car "+car);
System.out.println("carClone "+carClone);
}
}
运行测试程序,得到结果如下:
******************************************
car [year=5, brand=Brand [name=BMW]]
carClone [year=5, brand=Brand [name=BMW]]
******************************************
将car年限改为 7,品牌名称改为Banz
******************************************
car [year=7, brand=Brand [name=Banz]] carClone [year=5, brand=Brand [name=BMW]]
可见通过反序列化对象进行克隆也能得到我们想要的结果。