Java Serializable key points

1. 必须implements Serializable;html

2. 基本算法是:java

   a. 写出当前类的meta data算法

   b. 递归调用写出,直至java.lang.Object, 父类的meta dataoracle

   c. 写出实例字段信息code

3. 若是类中某个字段不能序列化,或者不须要序列化,将该字段标记为transistent。 除去transistent的其余字段, 包括private的,都会被序列化;htm

4. 对于已序列化的对象,增长/减小字段或者方法,反序列化会报错java.io.InvalidClassException;若是这样的变化是兼容的,那么能够提供一个字段serialVersionUID,给定肯定的一个值;若是是类的层级改变了,那么也是不能反序列化的;对象

5. 对象序列化和反序列化,可经过调用ObjectInputStream.readObject()/ObjectOutputStream.writeObject递归

FileOutputStream fos = new FileOutputStream("temp.out");
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		SerialTest st = new SerialTest();
		oos.writeObject(st);
		oos.flush();
		oos.close();
FileInputStream fis = new FileInputStream("temp.out");
	ObjectInputStream oin = new ObjectInputStream(fis);
	TestSerial ts = (TestSerial) oin.readObject();
	System.out.println("version="+ts.version);

6. 若是要对序列化作更多的控制,能够实现如下的方法:it

  • private void writeObject(ObjectOutputStream out) throws IOException;
  • private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

 

参考:io

1. https://www.javaworld.com/article/2072752/the-java-serialization-algorithm-revealed.html

2. http://www.oracle.com/technetwork/articles/java/javaserial-1536170.html

相关文章
相关标签/搜索