java对象的序列化和反序列化

1.当一个对象被序列化时,只保存对象的非静态成员变量,不能保存任何的成员方法和静态的成员变量。
2.如果一个对象的成员变量是一个对象,那么这个对象的数据成员也会被保存。
3.如果一个可序列化的对象包含对某个不可序列化的对象的引用,那么整个序列化操作将会失败,并且会抛出一个NotSerializableException。我们可以将这个引用标记为transient,那么对象仍然可以序列化。
4.如果想自己控制写入和读取对象,可以自己写readObject和writeObject方法(权限为private,java特例)。
Code:
  1. import java.io.*;  
  2.   
  3. public class ObjectSerialTest {  
  4.     public static void main(String[] args)throws Exception{  
  5.         Employee e1 = new Employee("zhangsan"253000.50);  
  6.         Employee e2 = new Employee("lisi"243200.40);  
  7.         Employee e3 = new Employee("wangwu"273800.55);  
  8.           
  9.         FileOutputStream fos = new FileOutputStream("D://java//employee.txt");  
  10.         ObjectOutputStream oos = new ObjectOutputStream(fos);  
  11.         oos.writeObject(e1);  
  12.         oos.writeObject(e2);  
  13.         oos.writeObject(e3);  
  14.         oos.close();  
  15.           
  16.         FileInputStream fis = new FileInputStream("D://java//employee.txt");  
  17.         ObjectInputStream ois = new ObjectInputStream(fis);  
  18.         Employee e;  
  19.         for(int i = 0; i < 3; i++){  
  20.             e = (Employee)ois.readObject();//反序列化的时候不会调用任何构造方法,Object转为Employee    
  21.             System.out.println("name:"+e.name+"/tage:"+e.age+"/tsalary:"+e.salary);  
  22.         }  
  23.         ois.close();  
  24.           
  25.     }  
  26.   
  27. }  
  28.   
  29. class Employee implements Serializable{  
  30.     String name;  
  31.     int age;  
  32.     transient double salary;  //不希望被保存的对象信息  
  33.     Employee(String name, int age, double salary) {  
  34.         this.name = name;  
  35.         this.age = age;  
  36.         this.salary = salary;  
  37.     }  
  38.     private void writeObject(java.io.ObjectOutputStream oos) throws IOException{  
  39.         oos.writeInt(age);  
  40.         oos.writeUTF(name);  
  41.         System.out.println("writeObject");  
  42.         //也可以采用不写入,相当于transient  
  43.     }  
  44.     private void readObject(java.io.ObjectInputStream ois) throws IOException{  
  45.         //按着写入的顺序读取  
  46.         age = ois.readInt();  
  47.         name = ois.readUTF();  
  48.         System.out.println("readObject");         
  49.     }  
  50. }  
 
 

 

 

 

你可能感兴趣的:(java对象的序列化和反序列化)