今天遇到这样一个问题
ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Object[] obj=new Object[3];
for(int i=0;i<boj.length;i++){
obj[i]=form.getObject();
obj[i].setP=i;
}
}
最后obj[0].getP、obj[1].getP、obj[2].getP结果都是3,困扰了我半天,最后终于发现原有所在。
Java中有以下语句 Object a=new A(); Object b=a; 这样一来a和b都指向同一个对象,并没有new一个新对象。通过a或b都可以改变对象。
解决问题的把法就是在循环里new一个对象,然后设置新对象的属性用ActionForm中的属性,对象属性若有几十个属性,一一设置很麻烦,幸好java.lang.Object对象有个clone方法,不过要实现java.lang.Cloneable接口。该接口没有任何方法。
简单的例子:浅克隆(对象的属性非用户自定义类型)
public class Person implements java.lang.Cloneable{
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
String string=this.name+"-"+this.age;
return string;
}
public Person clone() throws CloneNotSupportedException{
return (Person)super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException{
Person p1=new Person("aName",10);
Person p2=p1.clone();
p2.setName("leonard");
p2.setAge(100);
System.out.println(p1);
System.out.println(p2);
}
}
深度克隆(对象属性里有用户定义类型)结合上面的Person类
public class Family implements java.lang.Cloneable{
String name;
Person person;
public Family() {
// TODO Auto-generated constructor stub
}
public Family(String name,Person person){
this.name=name;
this.person=person;
}
public Family clone() throws CloneNotSupportedException{
Family family=(Family)super.clone();
family.person=this.person.clone();//关键的一步
return family;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
}
测试:
public static void main(String[] args) throws CloneNotSupportedException {
Person person=new Person("庄",29);
Family family=new Family();
family.setName("庄");
family.setPerson(person);
Family family2=(Family)family.clone();
family2.setName("严");
family2.getPerson().setName("严");
family2.getPerson().setAge(100);
System.out.println("a姓氏:"+family.getName()+" 后裔:"+family.getPerson());
System.out.println("a姓氏:"+family2.getName()+" 后裔:"+family2.getPerson());
}
深度克隆的前提:Family和Person都必须实现java.lang.Cloneable并重写Object的clone方法。
Family对象在调用super.clone()后,family1和family2是两个不同的对象,但是他们的Person属性确是指向同一个person,所以必须有下一步family.person=this.person.clone()来克隆一个Person对象,这样一来两个Family对象完全独立了。以此类推。