浅克隆
对于浅克隆,对象是克隆了,但是里面的类确实用的同一个,示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
public class Pig implements Cloneable {
private String name; private Date birthday;
public Pig(String name, Date birthday) { this.name = name; this.birthday = birthday; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Date getBirthday() { return birthday; }
public void setBirthday(Date birthday) { this.birthday = birthday; }
@Override public String toString() { return "Pig{" + "name='" + name + '\'' + ", birthday=" + birthday + '}'+super.toString(); }
@Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
public class Test { public static void main(String[] args) throws CloneNotSupportedException { Date birthday=new Date(0); Pig pig1=new Pig("佩奇",birthday); Pig pig2= (Pig) pig1.clone(); System.out.println(pig1); System.out.println(pig2); pig1.getBirthday().setTime(4839480394034L); System.out.println(pig1); System.out.println(pig2);
} }
|
输出
深克隆
1 2 3 4 5 6 7
| @Override protected Object clone() throws CloneNotSupportedException { Pig pig= (Pig) super.clone(); pig.birthday= (Date) pig.birthday.clone(); return pig; }
|
对克隆的反射攻击破坏单例模式
1 2 3 4 5 6
| HungrySingleton hungrySingleton=HungrySingleton.getInstance(); Method method = hungrySingleton.getClass().getDeclaredMethod("clone"); method.setAccessible(true); HungrySingleton hungrySingleton1 = (HungrySingleton) method.invoke(hungrySingleton); System.out.println(hungrySingleton); System.out.println(hungrySingleton1);
|
解决方案
1 2 3 4
| @Override protected Object clone() throws CloneNotSupportedException { return getInstance(); }
|
或者不实现Cloneable