简体   繁体   English

如何在java中克隆对象

[英]How to clone object in java

I want to create a list/array of object with the same parent class which then I will use it for reference. 我想创建一个具有相同父类的对象的列表/数组,然后我将它用于参考。 but i dont know how to clone those object to make a new object. 但我不知道如何克隆这些对象来制作一个新对象。

here is the example 这是一个例子

BigFoo a;
SmallFoo b;
ChickenFoo c;
List<Foo> foos;
foos.add(a);
foos.add(b);
foos.add(c);

Foo foo = foos.get(1).clone();

but in Java i found no clone function in the default function. 但在Java中我发现默认函数中没有克隆函数。 I wonder how this is accomplished? 我想知道这是如何实现的?

I suggest you read up on how to implement/expose the clone() method. 我建议你阅读如何实现/公开clone()方法。 http://download.oracle.com/javase/tutorial/java/IandI/objectclass.html http://download.oracle.com/javase/tutorial/java/IandI/objectclass.html

The general suggestion: use a copy constructor . 一般建议:使用复制构造函数 In fact, only a class itself knows how to create a clone of itself. 事实上,只有一个类本身知道如何创建自己的克隆。 No class can clone an instance of another class. 没有类可以克隆另一个类的实例。 The idea goes like this: 这个想法是这样的:

public class Foo {
  public List<Bar> bars = new ArrayList<Bar>();
  private String secret;

  // Copy constructor
  public Foo(Foo that) {
    // new List
    this.bars = new ArrayList<Bar>();

    // add a clone of each bar (as an example, if you need "deep cloning")
    for (Bar bar:that.bars) {
      this.bars.add(new Bar(bar));
    }

    // clone the secret value
    this.secret = new String(that.secret);
  }

  // ...

}

So if we want to clone a foo , we simply create a new one based on foo : 因此,如果我们想要克隆foo ,我们只需基于foo创建一个新的:

Foo clonedFoo = new Foo(foo);

That's the recommended way to clone an instance. 这是克隆实例的推荐方法。


copy constructor works well with inheritance. 复制构造函数适用于继承。 Consider a subclass 考虑一个子类

 public ChildFoo extends Foo {

   private int key;

   public ChildFoo(ChildFoo that) {
     super(that);
     this.key = that.key;
   }
 }

Foo has a copy constructor and ChildFoo simply calls it from it's own copy constructor. Foo有一个拷贝构造函数,而ChildFoo只是从它自己的拷贝构造函数中调用它。

Your example is possible but not advisable. 你的例子是可能的,但不可取。 What will happen: 会发生什么:

 Foo a = new Foo();
 ChildFoo b = new ChildFoo(a);  

This would require a constructor on ChildFoo like: 需要 ChildFoo上的构造函数,如:

 public ChildFoo(Foo that) {
     // call the copy constructor of Foo -> no problem
     super(that);

     // but how to initialize this.key? A Foo instance has no key value!
     // Maybe use a default value?
     this.key = 0;
 }

Technically not a challenge but b is not a clone of a because the objects don't have the same type. 从技术上讲不是一个挑战,但b不是克隆a ,因为对象不具有相同的类型。 So this (your example) is not cloning . 所以这(你的例子)不是克隆

一种简单的方法是使用json映射器(Jackson或Gson)并将对象写为字符串,然后使用字符串创建克隆对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM