杰歪JY丶 2017-01-04 08:53 采纳率: 50%
浏览 1330
已采纳

Java克隆对象失败,里面的对象属性没有克隆成功

想克隆一个输入流对象
类:
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还是同一个对象,如何克隆呢?

  • 写回答

4条回答 默认 最新

  • 「已注销」 2017-01-04 12:44
    关注

    斗胆来回答, 你的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;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵