今天调试程序,发现在解析的时候使用了clone函数,但是得到的结果是null,很奇怪。
看代码,override了clone函数,还是得到null。
继续搜索stackoverflow,发现没有增加Cloneable接口声明。
增加声明后,问题解决。
http://stackoverflow.com/questions/1052340/what-is-wrong-with-this-clone
The standard pattern for making a class cloneable is:
- Implement
Cloneable
- Override the
clone()
method and make it public - In
clone()
callsuper.clone()
and then copy any mutable object's state
You should not create a new object using new
. The proper way is to call super.clone()
for a new instance. Object
's clone()
is special and will create a new copy of the object and copy its primitive fields and references.
你不需要使用new关键字创建新对象。合适的方法是调用super.clone建立新对象。Object的clone()是特别的,会创建一个新的对象拷贝,以及拷贝它的基本类型和引用。(这里涉及到深拷贝和浅拷贝,请自行glgoo.com)
For example:
public class Person implements Cloneable {
protected String name;
// Note that overridden clone is public
public Object clone() {
Person clone = (Person)super.clone();
// No need to copy name as the reference will be
// copied by Object's clone and String is immutable
return clone;
}
}
public class Employee extends Person {
protected int id;
protected java.awt.Point location;
public Object clone() {
Employee clone = (Employee )super.clone();
// No need to copy id as Object's clone has already copied it
// Need to clone location as Point is mutable and could change
clone.location = location.clone();
return clone;
}
}