我尝试通过以下方法克隆对象:1)将其推入ByteArrayOutputStream; 2)将流分配给字节数组; 3)通过ByteArrayInputStream读取字节数组。但是,这将无法工作,因为我无法将OutputStream分配给字节数组,该行将无法执行。
Apporoach基于Java Serializable Object to Byte Array
public Bank clone() {
Bank objektKopie = null;
byte[] byteKopie = null;
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = null;
try {
bo = new ByteArrayOutputStream();
oo = new ObjectOutputStream(bo);
oo.writeObject(this);
oo.flush() ;
byteKopie = bo.toByteArray(); // THIS WILL NOT HAPPEN
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
bo.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
ByteArrayInputStream bi = new ByteArrayInputStream(byteKopie); // byteKopie IS STILL NULL
ObjectInputStream oi = null;
try {
oi = new ObjectInputStream(bi);
objektKopie = (Bank) oi.readObject();
} catch (Exception e) { System.out.println(e.getMessage()); }
return objektKopie;
}
答案 0 :(得分:0)
您的代码抛出“ NotSerializable”异常,您的班级银行需要实现Serializable
答案 1 :(得分:0)
如果依存关系还可以,GSON可以轻松做到这一点