实现 Cloneable接口深度克隆对象
Body对象中有Head对象,Head对象中有Face对象,Face对象中有int变量和String变量。
实现Boby对象的深度克隆,看下面代码:
package com.example.dumengen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ObjectClone {
protected static Logger logger= LoggerFactory.getLogger(ObjectClone.class);
public static class Body implements Cloneable{
public Head head;
public Body(Head head) {
this.head = head;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Body body = (Body) super.clone();
body.head = (Head) head.clone();
return body;
}
}
public static class Head implements Cloneable{
public Face face;
public Head(Face face) {
this.face = face;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Head head = (Head) super.clone();
head.face = (Face) face.clone();
return head;
}
}
public static class Face implements Cloneable{
public String str = "克隆";
public int a = 1;
public Face(String str, int a) {
String c = str+"";
this.str = c;
this.a = a;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws CloneNotSupportedException {
Body body = new Body(new Head(new Face("啊",2)));
Body body1 = (Body) body.clone();
logger.info("body == body1" +" " +(body == body1));
logger.info("body.head == body1.head" +" " +(body.head == body1.head));
logger.info("body.head.face == body1.head.face" +" " +(body.head.face == body1.head.face ));
logger.info("body.head.face.str == body1.head.face.str" +" " +(body.head.face.str == body1.head.face.str));
}
}