写java代码时,经常要实现对象的clone方法,处理对象的深拷贝问题。有一种简单的实现对象深拷贝的方法:将对象写入到字节流中,再读出来即可实现深拷贝。
@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T obj) {
T cloneObj = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ois = new ObjectInputStream(bais);
cloneObj = (T) ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (ois != null) {
try {
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return cloneObj;
}
执行此方法需要注意:
- 对象需要实现Serializable接口
- 对象内部的属性均可序列化
- 注意方法和属性的特殊修饰符。比如final、static变量的序列化问题会被引入到对象拷贝中。transient变量不会序列化。