Java Serializable Interface [转] 3

来源:互联网 发布:淘宝能统一更改运费吗 编辑:程序博客网 时间:2024/05/04 15:36

Java Serializable Interface [转] 3

可以看到,在序列化的时候,writeObject与readObject之间的先后顺序。readObject将最先write的object read出来。用数据结构的术语来讲就姑且称之为先进先出吧!

  在序列化时,有几点要注意的:
  1:当一个对象被序列化时,只保存对象的非静态成员变量,不能保存任何的成员方法和静态的成员变量。
  2:如果一个对象的成员变量是一个对象,那么这个对象的数据成员也会被保存。
  3:如果一个可序列化的对象包含对某个不可序列化的对象的引用,那么整个序列化操作将会失败,并且会抛出一个NotSerializableException。我们可以将这个引用标记为transient,那么对象仍然可以序列化

  还有我们对某个对象进行序列化时候,往往对整个对象全部序列化了,比如说类里有些数据比较敏感,不希望序列化,一个方法可以用transient来标识,另一个方法我们可以在类里重写

private   void  readObject(java.io.ObjectInputStream stream)
     
 throws 
 IOException, ClassNotFoundException;
 
 private   void 
 writeObject(java.io.ObjectOutputStream stream)
     
 throws 
 IOException

这二个方法!
  示例:

import  java.io. * ;

class  ObjectSerialTest
{
    
 public   static   void  main(String[] args)  throws  Exception
    
 {
        Employee e1
 = new  Employee( " zhangsan " , 25 , 3000.50 );
        Employee e2
 = new  Employee( " lisi " , 24 , 3200.40 );
        Employee e3
 = new  Employee( " wangwu " , 27 , 3800.55 );
        
        FileOutputStream fos
 = new  FileOutputStream( " employee.txt " );
        ObjectOutputStream oos
 = new  ObjectOutputStream(fos);
        oos.writeObject(e1);
        oos.writeObject(e2);
        oos.writeObject(e3);
        oos.close();
        
        FileInputStream fis
 = new  FileInputStream( " employee.txt " );
        ObjectInputStream ois
 = new  ObjectInputStream(fis);
        Employee e;
        
 for ( int  i = 0 ;i < 3 ;i ++ )
        
 {
            e
 = (Employee)ois.readObject();
            System.out.println(e.name
 + " : " + e.age + " : " + e.salary);
        }
 

        ois.close();
    }
 

}
 


class  Employee  implements  Serializable
{
    String name;
    
 int  age;
    
 double  salary;
    
 transient  Thread t = new  Thread();
    
 public  Employee(String name, int  age, double  salary)
    
 {
        
 this .name = name;
        
 this .age = age;
        
 this .salary = salary;
    }
 

    
 private   void  writeObject(java.io.ObjectOutputStream oos)  throws  IOException
    
 {
        oos.writeInt(age);
        oos.writeUTF(name);
        System.out.println(
 " Write Object " );
    }
 

    
 private   void  readObject(java.io.ObjectInputStream ois)  throws  IOException
    
 {
        age
 = ois.readInt();
        name
 = ois.readUTF();
        System.out.println(
 " Read Object " );
    }
 


}

原创粉丝点击