java使用序列化实现深克隆

java使用序列化实现深克隆

public static Object deepClone(Object source) {
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
File file = null;
try {
FileOutputStream fos = new FileOutputStream("objFile");
oos = new ObjectOutputStream(fos);
oos.writeObject(source);
FileInputStream fis = new FileInputStream("objFile");
ois = new ObjectInputStream(fis);
return ois.readObject();
} catch (Exception e) {
System.err.println("对象克隆失败");
e.printStackTrace();
return null;
} finally {
try {
if(null != oos) {
oos.close();
}
if(null != ois) {
ois.close();
}
file = new File("objFile");
if(null != file) {
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

你可能感兴趣的:(java使用序列化实现深克隆)