静态内置类可以达到线程安全的问题,但如果遇到序列化对象时,使用默认的方式运行得到的结果还是多例的。
import java.io.Serializable;
public class MyObject implements Serializable {
private static final long serialVersionUID = 888L;
private static class MyObjectHandler{
private static final MyObject myObject = new MyObject();
}
public MyObject() {
}
public static MyObject getInstance(){
return MyObjectHandler.myObject;
}
protected Object readResolve(){
System.out.println("调用了readResolve方法!");
return MyObjectHandler.myObject;
}
}
import java.io.*;
public class SaveAndRead {
public static void main(String[] args) {
try {
MyObject myObject = MyObject.getInstance();
FileOutputStream fosRef = new FileOutputStream(new File("D:\\data.txt"));
ObjectOutputStream oosRef = new ObjectOutputStream(fosRef);
oosRef.writeObject(myObject);
System.out.println(myObject.hashCode());
oosRef.close();
fosRef.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fisRef = new FileInputStream(new File("D:\\data.txt"));
ObjectInputStream iosRef = new ObjectInputStream(fisRef);
MyObject myObject = (MyObject) iosRef.readObject();
iosRef.close();
fisRef.close();
System.out.println(myObject.hashCode());
} catch (Exception e) {
e.printStackTrace();
}
}
}
来源:oschina
链接:https://my.oschina.net/projerry/blog/3165852