- 使用java的流,先将对象序列化,然后序列化回对象,其中的限制为克隆的对象必须实现Serializable接口
public Object deepCopy(Serializable source){
ObjectOutputStream os = null;
ObjectInputStream ois = null;
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(source);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
Object target = ois.readObject();
return target;
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
ois.close();
os.close();
} catch (IOException e) {
os = null;
ois=null;
}
}
return null;
}