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还是同一个对象,如何克隆呢?

斗胆来回答, 你的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;
    }

http://www.cnblogs.com/zc22/p/3484981.html
用深拷贝

你还只做了clone,目前对象是一样的,你还需要对ct2用setInputStream进行修改,这样才会两个对象的属性不一样

因为 CloneTest 只创建了一次,只有一个实例,你要克肯定要创建两个实例,只能进行克隆啊!