1.java序列化必须实现接口Serializable
2.序列化运行时使用一个称为 serialVersionUID 的版本号与每个可序列化类相关联,该序列号在反序列化过程中用于验证序列化对象的发送者和接收者是否为该对象加载了与序列化兼容的类。如果接收者加载的该对象的类的 serialVersionUID 与对应的发送者的类的版本号不同,则反序列化将会导致 InvalidClassException。可序列化类可以通过声明名为 “serialVersionUID” 的字段(该字段必须是静态 (static)、最终 (final) 的 long 型字段)显式声明其自己的 serialVersionUID:
class Animal implements Serializable {
private static final long serialVersionUID = -8334779167930920253L;
String a = "太阳";
public int eat() {
System.out.println("父吃饭");
return 0;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
//转存序列化后的文档
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Animal"));
oos.writeObject(new Animal());
oos.close();
//反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Animal"));
Animal p = (Animal)ois.readObject();
System.out.println( p.a);
}
打印结果:太阳
3.如果哪个属性不想序列化可以用transient修饰,即:
transient String a = “太阳”;的话打印结果为:null