2016-05-12 120 views
0
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(); 
    } 
} 

和`的Android - 類克隆不工作

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

我不能使用getClone()方法。我收到這個錯誤。我如何克隆一個實例?

java.lang.CloneNotSupportedException:Class UserWord不實現Cloneable。

修正:克隆:()方法需要實現IClonable inferface

+0

把這個,而不是超級,並嘗試 –

+0

顯示WordADT類請 –

+0

WordADT只是有幾個int變量 –

回答

0

用它來複制任何對象:

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); 
+0

爲什麼不使用內建克隆方法? –

+0

因爲內置克隆方法不克隆內部對象克隆。我認爲這是克隆根目錄中所有對象的一種非常好的方法。 – Sayem

+0

你認爲OP想要那樣做的是什麼? –