这招好使,深度clone不用一个个的set考虑关系了。
public static byte[] toByteArray(Object object) throws IOException {
if (object == null) return new byte[0];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(bos));
try {
oos.writeObject(object);
oos.flush();
return bos.toByteArray();
} finally {
bos.close();
oos.close();
}
}
public static Father fromByteArray(byte[] bytes) throws IOException, ClassNotFoundException {
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new ByteArrayInputStream(bytes)));
return (Father) ois.readObject();
} finally {
try {
if (ois != null) ois.close();
} catch (IOException e) {}
}
}
public byte[] toByteArray() throws IOException {
return toByteArray(this);
}
@Override
public Father clone() throws CloneNotSupportedException {
Father model = null;
try {
model = Father.fromByteArray(this.toByteArray());
} catch (Exception e) {
throw new CloneNotSupportedException(e.getMessage());
}
return model;
}