【问题标题】:Android - Class cloning not workingAndroid - 类克隆不起作用
【发布时间】:2016-09-08 02:37:01
【问题描述】:
public class UserWord extends WordADT {
     public int WORD_STATUS;
     public int POINT_OF_WORD;
     public int COUNT_OF_WRONG_ANSWER;

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

与`

Userword temp = new Userword();
Usertword temp2 = temp.getClone();          //this way doesn't work.

我不能使用 getClone() 方法。我收到这个错误。如何克隆实例?

java.lang.CloneNotSupportedException:UserWord 类没有实现 Cloneable。

固定: clone:() 方法需要实现IClonable inferface

【问题讨论】:

  • 用这个代替 super 试试
  • 请显示 WordADT 类
  • WordADT 只有几个 int 变量

标签: android class instance clone cloneable


【解决方案1】:

用它来克隆任何对象:

public static Object deepClone(Object object) {
    try {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        return ois.readObject();
    } catch (Exception e) {
        return null;
    }
}

在你的情况下使用如下:

Usertword temp2 = (Usertword)deepClone(temp);

【讨论】:

  • 为什么不使用内置的克隆方法?
  • 因为内置的克隆方法不会克隆内部对象克隆。我认为这是从根目录克隆所有对象的好方法
  • 是什么让你认为 OP 想要那个?
  • 帮了忙,tnx 兄弟
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 2013-06-12
  • 2018-12-12
  • 1970-01-01
  • 2012-12-21
  • 2016-12-12
  • 2014-08-22
相关资源
最近更新 更多