public class SingleTest implements Serializable{
private static final long serialVersionUID = -8600246627673134435L;
private static class SingleTestHandler{
private static SingleTest singleTest=new SingleTest();
public static SingleTest getInstance(){
return SingleTestHandler.singleTest;
/* protected Object readResolve(){
System.out.println("调用了readResolve方法!");
return SingleTestHandler.singleTest;
class MyThead extends Thread{
System.out.println(SingleTest.getInstance().hashCode());
public static void main(String[] args) {
SingleTest singleTest=SingleTest.getInstance();
FileOutputStream fileOutputStream=new FileOutputStream(new File("myObjectFilee.txt"));
ObjectOutputStream objectOutputStream=new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(singleTest);
objectOutputStream.close();
fileOutputStream.close();
System.out.println(singleTest.hashCode());
} catch (IOException e) {
FileInputStream fileInputStream=new FileInputStream(new File("myObjectFilee.txt"));
ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
SingleTest singleTest=(SingleTest) objectInputStream.readObject();
objectInputStream.close();
System.out.println(singleTest.hashCode());
} catch (IOException e) {
} catch (ClassNotFoundException e) {
-----------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------------
那么这个readResolve()方法是从哪来的,为什么加上之后就能返回同一实例了呢?
* Reads and returns "ordinary" (i.e., not a String, Class,
* ObjectStreamClass, array, or enum constant) object, or null if object's
* class is unresolvable (in which case a ClassNotFoundException will be
* associated with object's handle). Sets passHandle to object's assigned
private Object readOrdinaryObject(boolean unshared)
if (bin.readByte() != TC_OBJECT) {
throw new InternalError();
ObjectStreamClass desc = readClassDesc(false);
Class<?> cl = desc.forClass();
if (cl == String.class || cl == Class.class
|| cl == ObjectStreamClass.class) {
throw new InvalidClassException("invalid class descriptor");
obj = desc.isInstantiable() ? desc.newInstance() : null;
throw (IOException) new InvalidClassException(
desc.forClass().getName(),
"unable to create instance").initCause(ex);
passHandle = handles.assign(unshared ? unsharedMarker : obj);
ClassNotFoundException resolveEx = desc.getResolveException();
handles.markException(passHandle, resolveEx);
if (desc.isExternalizable()) {
readExternalData((Externalizable) obj, desc);
readSerialData(obj, desc);
handles.finish(passHandle);
handles.lookupException(passHandle) == null &&
desc.hasReadResolveMethod())
Object rep = desc.invokeReadResolve(obj);
if (unshared && rep.getClass().isArray()) {
handles.setObject(passHandle, obj = rep);
本文转自秋楓博客园博客,原文链接:http://www.cnblogs.com/rwxwsblog/p/6661719.html,如需转载请自行联系原作者