[英]Android - Class cloning not working
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();
}
}
AND`
Userword temp = new Userword();
Usertword temp2 = temp.getClone(); //this way doesn't work.
我不能使用getClone()方法。 我收到此錯誤。 如何克隆實例?
java.lang.CloneNotSupportedException:類UserWord不實現Cloneable。
固定: clone :()方法需要實現IClonable接口
用它來克隆任何對象:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.