是否有更快的深度复制技术可用于深度复制对象?我的类实现了Serializable
至于现在,我正在使用:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ObjectCloner {
// so that nobody can accidentally create an ObjectCloner object
private ObjectCloner() {
}
// returns a deep copy of an object
@MetricsLogger(enableSuccessMetrics = true)
static public Object deepCopy(Object oldObj) throws Exception {
ObjectOutputStream outputStream = null;
ObjectInputStream objectInputStream = null;
try {
if (oldObj != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
outputStream = new ObjectOutputStream(byteArrayOutputStream);
// serialize and pass the object
outputStream.writeObject(oldObj);
outputStream.flush();
ByteArrayInputStream bin = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(bin);
// return the new object
return objectInputStream.readObject();
} else {
return null;
}
} catch (Exception e) {
throw new RankingPolicyException("Exception while cloning : ", e);
} finally {
if (outputStream != null && objectInputStream != null) {
objectInputStream.close();
outputStream.close();
}
}
}
}
这样可以正常工作但性能相当慢。如果有更好的方法可以进行深层复制,请告诉我。