7

我想克隆给定的对象。

如果我这样做

public class Something{
    Object o; //set in the constructor
    public Something(Object o){
         this.o = o;}
    public Something clone() throws CloneNotSupportedException{
         Something temp = super.clone();
         if (o instanceof Cloneable) //important part
             temp.o = o.clone(); //important part
         else temp.o = o;
    }
}

这将不起作用,因为 o.clone() 受到保护。

如果我这样做

         if (o instanceof Cloneable) //important part
             temp.o = ((Cloneable)o).clone(); //important part

它也不起作用,因为 Cloneable 是一个空接口。

那么我如何让编译器相信你可以克隆 o?

4

5 回答 5

2

你不能,在实现 clone() 时,必须知道什么是克隆,必须知道实现类。

克隆的替代方法是使用具有相同问题的复制构造函数,您必须知道该类。

有人说不要使用克隆,有人说定义你自己的接口,例如:Copyable http ://c2.com/cgi/wiki?CloneableDoesNotImplementClone

于 2015-06-21T12:04:14.400 回答
2

如果可以实现 Serializable 接口,另一种选择是使用序列化。缺点当然是性能。

https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/SerializationUtils.html#clone(java.io.Serializable)

如果你不想使用 apache commons,你可以使用 ObjectOutputStream/ObjectInputStream 做同样的事情。

于 2015-06-21T12:10:00.780 回答
1

你可以用反射来做到这一点

//We need reflection
import java.lang.reflect.*;
    //This class is the backbone of the feature
    public class MyCloneable implements Cloneable {

        //A constructor. For the sake of simplicity, the constructor is an empty constructor.
        public MyCloneable() {}

        //We implement the clone method. This returns a clone
        protected Object clone() throws CloneNotSupportedException {
            //We need the class of the object
            class c = this.getClass();
            //We get the empty constructor of the object
            Constructor constructor = c.getConstructor(new Class[]{});
            //newClone will be the cloned object
            Object newClone = constructor.newInstance(new Object[]{});
            //We get the array of fields
            Field[] fields = c.getDeclaredFields();
            //We iterate the fields to copy them. You might want to close these too, but for the sake of simplicity I did not tackle with this issue
            for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) {
                //We copy the field values of this into the clone
                fields[fieldIndex].set(newClone, fields[fieldIndex].get(this));
            }
            //newClone is ready and kicking
            return newClone;
        }

        //We need this method to be able to reach the clone method publicly
        public Object runClone() throws CloneNotSupportedException {
            return this.clone();
        }

    }

此代码未经测试,欢迎任何观察。

您需要使用从 MyCloneable 继承的类的对象。

于 2015-06-21T12:31:15.937 回答
0

在 Java 中没有克隆对象的通用方法。该类型必须在其公共 API 中提供一个克隆方法(可能被调用clone()或其他;无关紧要),并且 Java 中没有此类类型的通用超类型。

于 2015-06-23T01:24:17.290 回答
-1

java.lang.Cloneable接口必须由我们要创建其对象克隆的类实现。如果我们不实现 Cloneable 接口,clone()方法将生成CloneNotSupportedException.

clone()方法在 Object 类中定义。该方法的语法clone()如下:

protected Object clone() throws CloneNotSupportedException

所以你的课应该是

public class Something implements Cloneable {

    private Object o; //set in the constructor

    public Something(Object o) {
        this.o = o;
    }

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

    public Object getObject() {
        return o;
    }

    public static void main(String[] args) {
        Something s = new Something("try");
        System.out.println(s.getObject());
        try {
            Something s2 = (Something) s.clone();
            System.out.println(s2.getObject());
        } catch (CloneNotSupportedException ex) {
            Logger.getLogger(Something.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
于 2015-06-21T12:13:51.293 回答