public class Prototype implements Serializable{
private static final long serialVersionUID = -463279279341581931L;
//浅复制
class BaseClass implements Cloneable{
private String str;
private Test test;
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Test implements Serializable{
private static final long serialVersionUID = 6246981145613357962L;
private String strTest;
public String getStrTest() {
return strTest;
}
public void setStrTest(String strTest) {
this.strTest = strTest;
}
}//深复制
class DeepClone implements Serializable{
private static final long serialVersionUID = 7494636598162913845L;
private String str;
private Test test;
public Object clone(){
Object obj = null;
ByteArrayOutputStream bo = new ByteArrayOutputStream();
try {
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
//若直接将byte[]数组传递过来,而这个byte数组不是使用ObjectOutputStream类写入的就会报错。
//问题解决的办法就是:用输出流得到byte[]数组。
byte[] b = bo.toByteArray(); //不能自己new一个byte
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream oi = new ObjectInputStream(bi);
obj = oi.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return obj;
}
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
}
public static void main(String[] args){
Prototype prototype = new Prototype();
BaseClass baseClass = prototype.new BaseClass();
Integer a = new Integer(3);
Integer b = new Integer(4);
Test test = prototype.new Test();
test.setStrTest("test");
// try {
// baseClass.setStr("abcde...");
// baseClass.setTest(test);
// BaseClass baseClass2 = (BaseClass) baseClass.clone();
// System.out.println(baseClass2.getStr());
// System.out.println(baseClass.getClass() == baseClass2.getClass());//同类型
// System.out.println(baseClass.equals(baseClass2));
// System.out.println(baseClass == baseClass2);
// System.out.println(a.getClass() == b.getClass());
// baseClass2.getTest().setStrTest("test2");
// System.out.println(baseClass.getTest().getStrTest());
// System.out.println(baseClass2.getTest().getStrTest());
// } catch (CloneNotSupportedException e) {
// e.printStackTrace();
// }
DeepClone deep = prototype.new DeepClone();
deep.setTest(test);
DeepClone deep2 = (DeepClone) deep.clone();
System.out.println("....");
System.out.println(deep2.getTest().getStrTest());
System.out.println(deep.getTest().getStrTest());
deep2.getTest().setStrTest("test2");
System.out.println(deep2.getTest().getStrTest());
System.out.println(deep.getTest().getStrTest());
}
}