JAVA对象序列化(Serializable、ObjectOutputStream、ObjectInputStream、 transient)

1)对象序列化是把一个对象变为二进制的数据流的一种方法。对象序列化后可以方便的实现对象的传输或存储。

2)如果一个类的对象想被序列化,则对象所在的类必须实现Serialilzable接口。此接口中没有定义任何方法,所以此借口是一个标识接口,表示一个类具备被序列化的能力。

3)对象被序列化后变为二进制,可以经过二进制数据流进行传输。此时必须依靠对象输出流(ObjectOutputStream)和对象输入流(ObjectInputStream)。

4)在序列化中,只有属性被序列化。因为每个对象都具有相同的方法,但是每个对象的属性是不相同的,也就是说,对象保存的只有属性信息,所以在序列化时,只有属性被序列化。

 1 public class Person implements Serializable {
 2     private String name;
 3     private int age;
 4     public Person(String name,int age){
 5         this.name = name;
 6         this.age = age;
 7     }
 8     public String toString(){
 9         return this.name + "....." + this.age;
10     }
11 }
 1 import java.io.File;
 2 import java.io.FileNotFoundException;
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 import java.io.ObjectOutputStream;
 6 import java.io.OutputStream;
 7 
 8 public class SerDemo01 {
 9     
10     public static void main(String[] args) throws Exception {
11         File f = new File("D:" + File.separator + "test.txt");
12         ObjectOutputStream oos = null;
13         OutputStream out = new FileOutputStream(f);
14         oos = new ObjectOutputStream(out);
15         oos.writeObject(new Person("zhangsan",30));
16         oos.close();
17     }
18 
19 }
 1 import java.io.File;
 2 import java.io.FileInputStream;
 3 import java.io.InputStream;
 4 import java.io.ObjectInputStream;
 5 
 6 public class SerDemo02 {
 7 
 8     public static void main(String[] args) throws Exception{
 9         File f = new File("D:" + File.separator + "test.txt");
10         ObjectInputStream ois = null;
11         InputStream input = new FileInputStream(f);
12         ois = new ObjectInputStream(input);
13         Object obj = ois.readObject();
14         ois.close();
15         System.out.println(obj);
16     }
17 
18 }

输出结果为:张三.....30

如果一个对象的某些属性不希望被序列化,则可以使用transient关键字进行声明,

如果将上述Person类中的private String name;修改为private transient String name;

最后输出的结果为:null.....30

原文地址:https://www.cnblogs.com/XuGuobao/p/7226098.html