不爱吃土豆尼 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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。