package p1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class SerializationCheck {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
SingletonCompanyCEO s1 = SingletonCompanyCEO.getSingleObject();
SingletonCompanyCEO s2 = SingletonCompanyCEO.getSingleObject();
System.out.println("s1==s2:"+(s1==s2));
ObjectOutputStream obs = new ObjectOutputStream(new FileOutputStream("file.txt"));
obs.writeObject(s1);
//first read from file
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file.txt"));
SingletonCompanyCEO ceo = (SingletonCompanyCEO)ois.readObject();
//second read from file
ois = new ObjectInputStream(new FileInputStream("file.txt"));
SingletonCompanyCEO ceo1 = (SingletonCompanyCEO)ois.readObject();
System.out.println("ceo==ceo1:"+(ceo==ceo1)+" (read from file ie. de-serialized)");
System.out.println(ceo1);
}
}
class SingletonCompanyCEO implements Serializable
{
public void setName(String name){
this.name = name;
}
public Object readResolve() throws ObjectStreamException {
return singleObject;
}
private static final long serialVersionUID = 1L;
private transient int age = 55; // age should set to zero by default as age is transient. But it is not happening, any reason?
private String name ="Amit";
float salary = 0f;
private static SingletonCompanyCEO singleObject;
private SingletonCompanyCEO()
{
if(singleObject!=null)
{
throw new IllegalStateException();
}
}
public static SingletonCompanyCEO getSingleObject()
{
if(singleObject==null)
{
singleObject = new SingletonCompanyCEO();
}
return singleObject;
}
public String toString()
{
return name+" is CEO of the company and his age is "+
age+"(here 'age' is transient variable and did not set to zero while serialization)";
}
}
将此代码复制并粘贴到eclipse编辑器中。 序列化时默认'age'transient
变量未设置为零的原因是什么?
序列化表示在序列化时瞬态和静态变量设置为零(或默认值)。
解序列化后,我得到age = 55
而不是age = 0
。
JLS背后必有理由。它是什么?为什么瞬态变量的状态存储在单例对象中?
同意。执行上面的代码,然后删除s1和s2引用创建的代码,并删除写入对象的代码。现在我们已经序列化了包含对象的文件。 删除后,我们只有文件阅读代码。现在我发现对象没有被创建,'null'正在读取文件后返回。现在再次尝试删除readResolve(),然后你会发现对象正在创建,而不是单身。它是什么? – AmitG 2013-02-21 08:22:28
@AmitG:查看我的更新。 – 2013-02-21 08:50:01
好的。同意。但是如果我们保持readResolve()方法,那么对象将从文件中变为'null'。怎么样? 如何反序列化Singleton对象,以便每个JVM只能获取实例? 如果我们保持readResolve()两个对象的创建,并且如果我们不保存readResolve(),则不会创建任何对象。 – AmitG 2013-02-21 10:36:34