Java:对象克隆问题?

时间:2012-08-08 20:41:04

标签: java clone

我有invoice个对象,它有两个属性,productDescriptionproductQuantity,这里是代码:

public class Invoice() implements Cloneable
{
  private String productDescription;
  private int productQuantity;

  //Getters & Setters

  public Object clone() throws CloneNotSupportedException {
     return super.clone();
  }
}

现在我想在这个类上创建对象的副本,所以我正在做

Invoice invoiceCopy = (Invoice)invoice.clone();

现在,如果我更新invoiceCopy.setProductQuanity = 10的值,那么invoice也会更新值,但不应该发生任何建议?

更新代码

public class Invoice implements Cloneable {
    private String productDescritpion;
    private int productQuantity;

    public String getProductDescritpion() {
        return productDescritpion;
    }

    public void setProductDescritpion(String productDescritpion) {
        this.productDescritpion = productDescritpion;
    }

    public int getProductQuantity() {
        return productQuantity;
    }

    public void setProductQuantity(int i) {
        this.productQuantity = i;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public static void main(String[] args) {
        Invoice invoice = new Invoice();
        invoice.setProductQuantity(10);
        invoice.setProductDescritpion("nike");
        Invoice invoiceCopy = null;
        try {
            invoiceCopy = (Invoice) invoice.clone();
        } catch (CloneNotSupportedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        invoiceCopy.setProductQuantity(20);
        System.out.println("Invoice quantity: " + invoice.getProductQuantity());
        System.out.println("InvoiceCopy quantity: "
                + invoiceCopy.getProductQuantity());
    }
}

2 个答案:

答案 0 :(得分:0)

默认克隆方法是一种肤浅的方法。 你必须自己编写一个新方法或使用一个你想要的库(参见apache的BeanUtils例子)

如果你想写它,尝试类似:

public class Invoice implements Cloneable {
private String productDescription;
private int productQuantity;

public Invoice() {
}

public Invoice(Invoice copy) {
    productDescription = copy.productDescription;
    productQuantity = copy.productQuantity;
}

public Object clone() throws CloneNotSupportedException {
    return new Invoice(this);
}

}

答案 1 :(得分:-1)

您只是调用clone()的{​​{1}}方法,这对您的班级无效。您需要返回对象的新实例:

Object

我添加了构造函数来传递参数。