객체의 클론 생성

3165 단어
객체의 클론을 만드는 방법에는 두 가지가 있습니다.
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;
	}
	@Override
	public 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;
	}
	@Override
	public 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]]

좋은 웹페이지 즐겨찾기