package cn.junco.lang;
public class CloneClass { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Professor p=new Professor("xiaoyang",50);
Student s1=new Student("zs",30,p);
System.out.println(s1.name+"  "+s1.age);
Student s2=(Student)s1.clone();
s2.name="lisi";
s2.age=2;
System.out.println(s2.name+"  "+s2.age);

}
}class Professor implements Cloneable
{
 String name;
 int age;
Professor(String name,int age) {
// TODO Auto-generated constructor stub
 this.name=name;
 this.age=age;
}
 public Object clone()
{
Object o=null;
try {
o=super.clone();
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return o;
}
}
class Student  implements Cloneable{
String name;
int age;
Professor p;
Student(String name,int age,Professor p) {
// TODO Auto-generated constructor stub
    this.p=p;
this.name=name;
this.age=age;

}

public Object clone()
{
Object o=null;
try {
o=(Student)super.clone();

} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
o.p=(Professor)p.clone();///这里提示出错o.p cannot be resolved or is not a field,请问是怎么回事啊?

return o;
}


}

解决方案 »

  1.   

    这样因该是不行的.掉用super.clone()就已经把该对象中的对象属性的引用也复制了一份.
    可以通过ByteArrayOutputStream()把对象写出去,再读回来
    深拷贝
      

  2.   

    ObjectOutputStream os =null;
    ObjectInputStream ois=null;
    try {
    ByteArrayOutputStream bs = new ByteArrayOutputStream();
     os = new ObjectOutputStream(bs);
    os.writeObject(this);
    byte[] b=bs.toByteArray();

    ByteArrayInputStream as = new ByteArrayInputStream(b);
     ois=new ObjectInputStream(as);
    Object o = ois.readObject();
    return o;
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return null;
    } catch (ClassNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    return null;
    }
    finally{
    try {
    if(os!=null)os.close();
    if(ois!=null)ois.close();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }