我想克隆給定的對象。我如何說服編譯器的對象是可複製的(java)?
如果我這樣做
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?
@immibis,我不認爲你的評論增加了很多值得坦白的。 – aioobe
你必須讓你的類實現'Cloneable'並實現'clone'方法。 – Rishav
來自doc:「一個類實現了Cloneable接口,以向Object.clone()方法表明,該方法爲該類的實例的字段 - 場複本創建是合法的。」 – Rishav