java序列化的(二)

来源:互联网 发布:qq怎么设置mac在线最新 编辑:程序博客网 时间:2024/05/16 06:39


java如果多次序列化一个对象,只有第一次序列化时才把该java对象转换成字节序列并输出,而以后的序列化只是输出一个编号而已。

1.自定义序列化

(1)被序列化的类中属性用transient修饰时,该属性将完全隔离在序列化之外。下面是个例子:

public class TransientPer {public static void main(String[] args){ObjectOutputStream oos=null;ObjectInputStream ois=null;try{//下面三行就是对象实现序列化并输出到文件中的一般操作oos=new ObjectOutputStream(new FileOutputStream("object.txt"));Person ps=new Person("qianhao",18);//将对象输出到输出流,放到了object.txt文件oos.writeObject(ps);ois=new ObjectInputStream(new FileInputStream("object.txt"));Person p=(Person)ois.readObject();System.out.println(p.getAge());}catch(Exception e){e.printStackTrace();}finally{try{if(oos!=null){oos.close();}if(ois!=null){ois.close();}}catch(Exception e1){e1.printStackTrace();}}}}

按道理输出age应该为18,但是由于age被transient所修饰,所以age没有被序列化与反序列化。所以输出age为0

2.java的序列化机制保证在序列化某个对象之前,先调用该对象的writePlace方法(该方法在被序列化的类中进行复写),如果该方法返回另一个java对象,则系统转为序列化另一个java对象

0 0