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 中,这背后一定是有原因的。它是什么?