java的对象复制有两种方式:实现Serializable和实现Cloneable。
两者都能实现对象的复制,但是各有利弊:
1. 实现Cloneable必须实现clone()方法,clone方法复制对象非常简单,但是这样会对原始对象有侵入性,不利于对象的扩展:假设有一个新对象继承实现Cloneable的对象,那么新对象想要实现复制,就必须重写clone()方法。
2. 实现Serializable在复制对象时,方法相对复杂,需要使用ByteArrayOutputStream、ObjectOutputStream、ByteArrayInputStream、ObjectInputStream等类,但是无侵入性。
package com.sg.deepcopy;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
/**
* <b>DeepCopy.java</b>
* @author yanlei
* @version 1.0 Jun 9, 2012
*/
public class DeepCopy {
public static Object streamCopy(Object obj) throws IOException, ClassNotFoundException{
//初始化输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(out);
//将对象写入缓存
objOut.writeObject(obj);
objOut.flush();
objOut.close();
//初始化输入流
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream objIn = new ObjectInputStream(in);
//构造对象
return objIn.readObject();
}
public static CloneUser cloneCopy(CloneUser user) throws CloneNotSupportedException {
return (CloneUser) user.clone();
}
public static void main(String[] args) throws IOException, ClassNotFoundException, CloneNotSupportedException {
System.out.println("//使用字节流复制");
User user1 = new User("zhangsan");
System.out.println("user1的hash值" +user1);
User user2 = (User)streamCopy(user1);
System.out.println("user2的hash值" +user2);
System.out.println("//使用clone方法复制");
CloneUser cloneUser1 = new CloneUser("lisi");
System.out.println("cloneUser1的hash值" +cloneUser1);
CloneUser cloneUser2 = cloneCopy(cloneUser1);
System.out.println("cloneUser2的hash值" +cloneUser2);
}
}
class User implements Serializable{
public User(){}
public User(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class CloneUser implements Cloneable {
public CloneUser(){}
public CloneUser(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}