java规定要使对象具有clone能力必须显式的定义它的clone能力,所以如果你的func方法传入的参数是Object类型则不能clone 你可以这么做: public class CloneTest { Object data; public void func(Object obj) { if (obj instanceof MyObject) { data = ((MyObject) obj).clone(); } else { data = obj; } } } class MyObject implements Cloneable { public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { return null; } } }
对象的复制涉及很多问题,楼主可以去翻阅think in java,有很大一部分章节介绍这个内容
when we develop our projects, we have almost all classes extends the top root class, DObject. DObject extends Object by default which does not need to be specified. DObject then implements Serializable and Cloneable. So, the clone() method is implemented in our DObject class. We implemented it using java reflect package, so there's no need to write own clone() for any other Classes extending DObject. And, they are all able to clone. DObject has a control in order not to hit an infinite loop. The simplest solution is to give a depth control. That's exactly how we coded in our 1.0 version. In our 2.0 version, we've used a pool to indicate whether we have cloned the Object or not. The full clone is satisfied.
你试过吗?
class obj extends Object
呢?
如果时一般的clone(),想要实现只要将你的类实现cloneable接口,再重载object的clone()方法为public就可以了。
如:
class MyObject implements Cloneable
{
int i;
MyObject(int ii)
{
i = ii;
}
public Object clone()//clone()方法必须是public的
{
Object o = null;
try
{
o = super.clone();//这句代码时必须的
}
catch(CloneNotSupportedException e)
{
System.err.println("MyObject can't clone");
}
return o;
}
}
你可以这么做:
public class CloneTest {
Object data;
public void func(Object obj) {
if (obj instanceof MyObject) {
data = ((MyObject) obj).clone();
} else {
data = obj;
}
}
}
class MyObject implements Cloneable {
public Object clone() {
try {
return super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
}
DObject extends Object by default which does not need to be specified.
DObject then implements Serializable and Cloneable. So, the clone() method is implemented in our DObject class.
We implemented it using java reflect package, so there's no need to write own clone() for any other Classes extending DObject. And, they are all able to clone.
DObject has a control in order not to hit an infinite loop. The simplest solution is to give a depth control. That's exactly how we coded in our 1.0 version. In our 2.0 version, we've used a pool to indicate whether we have cloned the Object or not. The full clone is satisfied.