1、java对象序列化不保存对象中的静态变量
serpublic class Test implements Serializable {
private static final long serialVersionUID = 1L;
public static int staticVar = 5;
public static void main(String[] args) {
try {
//初始时staticVar为5
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream("result.obj"));
out.writeObject(new Test());
out.close();
//序列化后修改为10
Test.staticVar = 10;
ObjectInputStream oin = new ObjectInputStream(new FileInputStream(
"result.obj"));
Test t = (Test) oin.readObject();
oin.close();
//再读取,通过t.staticVar打印新的值
System.out.println(t.staticVar);//10
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
2、虚拟机是否允许反序列化,不仅取决于类路径和功能代码是否一致,一个非常重要的一点是两个类的序列化 ID 是否一致(就是 private static final long serialVersionUID = 1L)。
3、父类的序列化与transient关键字
只有子类和父类都实现了Serializable接口时,对子类反序列化时才会将父类也序列化。反序列化过程是先反序列过父类对象再反序列化子类。而如果不想序列化某一个变量,则可以在定义变量时使用transient关键字。
Parentimport java.io.Serializable;
public class Parent implements Serializable {
private static final long serialVersionUID = 1L;
public int pi = 2;
public String pstr ="pstr";
public transient String ts ;
}
Son and mainimport java.io.File;
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.Serializable;
public class Son extends Parent implements Serializable {
private static final long serialVersionUID = 1L;
public int si = 1;
public String sstr = " sstr";
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
String path = "d:" + File.separator + "son.dll";
Son s = new Son();
s.si = 2;
s.pi = 2;
s.ts = "ts"; // ts在父类中的定义使用transient关键字
ObjectOutputStream op = null;
ObjectInputStream oi = null;
op = new ObjectOutputStream(new FileOutputStream(new File(path)));
op.writeObject(s);
op.close();
oi = new ObjectInputStream(new FileInputStream(path));
Son s1 = (Son) oi.readObject();
System.out.println("父类中的String pstr:" + s1.pstr);
System.out.println("父类中的int pi:" + s1.pi);
System.out.println("子类中的int si:" + s1.si);
System.out.println("父类中的transient String ts :" + s1.ts);//
}
}
4、Java 序列化机制为了节省磁盘空间,具有特定的存储规则,当写入文件的为同一对象时,并不会再将对象的内容进行存储,而只是再次存储一份引用。
从IBM DW 整理而来
http://www.ibm.com/developerworks/cn/java/j-lo-serial/index.html#icomments