假如你想保存一个对象(object),则这个对象所属类必须实现Serializable接口。
当串行化一个对象时,Java会保存对象的完整的“对象图”,即对该对象引用的其他对象,也进行串行化。当然,那些“其他对象”也要实现Serializable接口,否者抛NotSerializableException异常。
java 代码
- import java.io.*;
- public class A{
- public static void main(String [] args){
- Dog d = new Dog();
- Dog d2 = new Dog();
- try{
- FileOutputStream fos = new FileOutputStream("E:\\doc\\dogs.dat");
- ObjectOutputStream oos =new ObjectOutputStream(fos);
- oos.writeObject(d) ;
- oos.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- try{
- FileInputStream fis =new FileInputStream("E:\\doc\\dogs.dat");
- ObjectInputStream ois = new ObjectInputStream(fis);
- d2 = (Dog)ois.readObject();
- ois.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- System.out.println("name:"+d2.name+" age:"+d2.age+" shout:"+d2.shout());
- }
- }
- class Dog extends Animal implements Serializable{
- String name ="Peter";
- int age = 5;
- String shout(){
- return "Ho~Ho~";
- }
- }
- //Animal必须是实现Serializable
- class Animal implements Serializable{
- String name = "Unknown";
- Animal(){
- System.out.println("Animal构造函数运行");
- }
- }
实现了Serialiable接口的超类,在串行化时不会运行构造函数。没有实现了Serialiable接口的超类,否则会运行其构造函数。(每当实例化一个子类对象时,父类的构造函数将先于子类的构造函数被调用。)
添加标识transient 的变量 将不会被串行化,当该变量所属对象被反串行化时,该变量变为其数据类型的默认值。(String默认值为null,int为0.)
串行化不适合静态变量,它只针对实例对象。