不爱吃土豆尼 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 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作