有效的 Java - 为了保持单例保证,您必须声明所有实例字段瞬态并提供“readResolve”方法。通过在这里声明字段瞬态我们可以实现什么?这是一个示例:
....
....
public final class MySingleton implements Serializable{
private int state;
private MySingleton() { state =15; }
private static final MySingleton INSTANCE = new MySingleton();
public static MySingleton getInstance() { return INSTANCE; }
public int getState(){return state;}
public void setState(int val){state=val;}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
public static void main(String[] args) {
MySingleton c = null;
try {
c=MySingleton.getInstance();
c.setState(25);
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MySingleton) ois.readObject();
ois.close();
System.out.println("after deser: contained data is " + c.getState());
} catch (Exception e) {
e.printStackTrace();
}
}
}
无论我是否将“状态”变量声明为瞬态,我都会将 c.getState() gettign 打印为 25。我在这里遗漏了什么吗?