想克隆一個輸入流對象
類:
class CloneTest implements Cloneable{
public InputStream inputStream = null;
public CloneTest(InputStream inputStream){
this.inputStream = inputStream;
}
public Object clone() throws CloneNotSupportedException {
CloneTest cloneTest = (CloneTest)super.clone();
return cloneTest;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
}
調用的代碼:
CloneTest ct = new CloneTest(inputStream);
CloneTest ct2 = (CloneTest)ct.clone();
InputStream inputStream2 = ct2.getInputStream();
這裡得到的inputStream2和傳進去的參數inputStream還是同一個對象,如何克隆呢?
斗膽來回答, 你的clone方法中只是簡單的調用了CloneTest的父類的clone方法,
這裡jvm並不會自動復制你的InputStream屬性.如果你需要克隆後的對象和克隆
前的對象引用不同的InputStream對象,那麼你需要自己編碼復制該InputStream
對象.
就像下面這樣
public Object clone() throws CloneNotSupportedException {
CloneTest cloneTest = (CloneTest) super.clone();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
try {
while ((len = inputStream.read(buffer)) > -1 ) {
baos.write(buffer, 0, len);
}
baos.flush();
} catch (IOException e) {
e.printStackTrace();
}
InputStream is = new ByteArrayInputStream(baos.toByteArray());
cloneTest.setInputStream(is);
return cloneTest;
}