package morepackages;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Dog implements Serializable {
private static final long serialVersionUID = 1543076121788778204L;
private Dog() {
}
public static final Dog INSTANCE = new Dog();
public String toString() {
return "Woof";
}
/*
* 不加下面的方法就会返回 false;在反序列化的时候会创建一个新的对象
*/
private Object readResolve() {
return INSTANCE;
}
}
public class CopyDog {
public static Object deepCopy(Object obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new ObjectOutputStream(bos).writeObject(obj);
ByteArrayInputStream bin = new ByteArrayInputStream(
bos.toByteArray());
return new ObjectInputStream(bin).readObject();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
public static void main(String args[]) {
Dog newDog = (Dog) deepCopy(Dog.INSTANCE);
System.out.println(newDog == Dog.INSTANCE);
System.out.println(newDog);
}
}
/*
* 反序列化就是构造,一定会生成一个新的对象,但可以用 readResolve返回返序列化的对象
*/
当单例遇到了反序列化
最新推荐文章于 2022-07-02 22:53:34 发布