0

我有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 = 10theninvoice也会更新值,但这不应该发生,有什么建议吗?

更新代码

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());
    }
}
4

2 回答 2

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);
}

}

于 2012-08-08T20:49:16.343 回答
-1

您只是在调用对您的班级没有任何作用的clone()方法。Object您需要返回对象的新实例:

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

  public Invoice() {

  }

  private Invoice(String productDescription, int productQuantity) {
    this.productDescription = productDescription; 
    this.productQuantity = productQuantity;

  //Getters & Setters

  public Object clone() throws CloneNotSupportedException {
     return new Invoice(productDescription, productQuantity);
  }
}

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

于 2012-08-08T20:46:36.087 回答