對於類別的完整複製而言,如果該類別有許多的類別變數(Field),則在重新定義Clone() 方法時逐個複製將會是一件非常麻煩的工作。
序列化可以將任意物件(Object) 寫入到Stream 中,根據不同的Stream可以將其寫入到檔案中或者 Bytes Array。
利用序列化複製物件時不需要先進行儲存,因此先將其轉成 Bytes Array ,寫入完成後再將其讀取而出即可完成複製動作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class Address implements Serializable{ private static final long serialVersionUID = 4983187287403615604L; private String stateString; private String cityString; public Address(String state,String city) { this.stateString = state; this.cityString = city; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("°ê®a:" + stateString); sb.append(" " + cityString); return sb.toString(); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
public class Employee implements Cloneable,Serializable{ private static final long serialVersionUID = 3049633059823371192L; private String nameString; private int age; private Address address; public Employee(String name,int age,Address address) { this.nameString = name; this.age = age; this.address = address; } @Override public String toString() { // TODO Auto-generated method stub StringBuilder sb = new StringBuilder(); sb.append("姓名 : " + this.nameString); sb.append("年齡 : " + this.age); sb.append("地址 : " + address ); return address.toString(); } @Override public Employee clone() { Employee employee = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); oos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); try { ObjectInputStream ois = new ObjectInputStream(bais); employee = (Employee) ois.readObject(); ois.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return employee; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Test { public static void main(String[] args) { out.println("複製前: "); Address address = new Address("台灣", "台南"); Employee employee1 = new Employee("OO科技", 18, address); out.println("員工 1 : "); out.println(employee1); out.println("複製後 : "); Employee employee2 = employee1.clone(); out.println("員工 2 : "); out.println(employee2); } } |
文章標籤
全站熱搜
留言列表