是单一类还是需要对所有的类?你需要做deep clone,实现Cloneable,实现public Object clone() , 参考http://www.churchillobjects.com/c/11091d.html或参考 How can I do a deep clone of an object? http://www.jguru.com/faq/view.jsp?EID=20435 YourClasa a = ..; YourClass b = (YourClass)a.Clone(); try { a.setProperty(xxx); } catch (SomeException ex) { a = (YourClass)b.Clone(); }
这样就不用一个个的写了。
How can I do a deep clone of an object?
http://www.jguru.com/faq/view.jsp?EID=20435
YourClasa a = ..;
YourClass b = (YourClass)a.Clone();
try
{
a.setProperty(xxx);
}
catch (SomeException ex)
{
a = (YourClass)b.Clone();
}
把b clone一份了,然后把这个副本付给a,a=b.clone()。特别强调一点,java中a,b是引用变量,仅仅是指向某一个对象而已,本身并不是什么对象。
private double depth;
public DepthReading(double depth) {
this.depth = depth;
}
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch(CloneNotSupportedException e) {
e.printStackTrace(System.err);
}
return o;
}
}class TemperatureReading implements Cloneable {
private long time;
private double temperature;
public TemperatureReading(double temperature) {
time = System.currentTimeMillis();
this.temperature = temperature;
}
public Object clone() {
Object o = null;
try {
o = super.clone();
} catch(CloneNotSupportedException e) {
e.printStackTrace(System.err);
}
return o;
}
}class OceanReading implements Cloneable {
private DepthReading depth;
private TemperatureReading temperature;
public OceanReading(double tdata, double ddata){
temperature = new TemperatureReading(tdata);
depth = new DepthReading(ddata);
}
public Object clone() {
OceanReading o = null;
try {
o = (OceanReading)super.clone();
} catch(CloneNotSupportedException e) {
e.printStackTrace(System.err);
}
// Must clone references:
o.depth = (DepthReading)o.depth.clone();
o.temperature = (TemperatureReading)o.temperature.clone();
return o; // Upcasts back to Object
}
}public class DeepCopy {
public static void main(String[] args) {
OceanReading reading =
new OceanReading(33.9, 100.5);
// Now clone it:
OceanReading r =
(OceanReading)reading.clone();
}
}=============================================
这是thinking in java上的深层COPY的代码,要Clone得进行下面的步骤:1.要clone的类得实现Cloneable接口2.override colne这个方法并让它成为public3.在此方法中调用super.clone();
如果对象a又由其它引用了,如request.setAttribute("c",a);
那么在做a=b的后重新做request.setAttribute("c",a);的引用。否则就需要为a的属性赋值了,而不能使用a=b的方式。