public class CloneDemo { public static void main(String[] args) { B b = new B(); b.setName("B name"); A a1 = new A(); a1.setB(b); a1.setName("A name"); A a2 = a1.cloneMyself(); System.out.println(a1 == a2);//false System.out.println(a1.getB() == a2.getB());//false } } class A implements Serializable{ /** * */ private static final long serialVersionUID = -1556039944244358522L; private String name; private B b; public String getName() { return name; } public void setName(String name) { this.name = name; } public B getB() { return b; } public void setB(B b) { this.b = b; } //Provide clone method public A cloneMyself(){ A a = null; try { /** * Write the object to the memory array */ ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); /** * Read the data in the memory array and convert it into an object */ ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); a = (A) ois.readObject(); } catch (IOException e) { e.printStackTrace (); } catch (ClassNotFoundException e) { e.printStackTrace (); } return a; } } class B implements Serializable{ /** * */ private static final long serialVersionUID = -1984117425001746882L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
JAVA clone small instance
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=325963766&siteId=291194637
Ranking