Java序列化

(虽然java序列化没有在实际工作中使用过,但是面试的时候可能会问到,这里还是把一些基本知识总结记录一下。)

实现一个序列化其实只需要实现 Serializable 接口即可。只要这个类实现了Serializable接口,这个的所有属性和方法都会自动序列化。如果类中的某个属性不需要进行序列化,将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。

代码举例:

实体类:检验一个类的实例是否能序列化十分简单, 只需要查看该类有没有实现 java.io.Serializable接口。

 1 public class Employee implements java.io.Serializable
 2 {
 3    public String name;
 4    public String address;
 5    public transient int SSN; //不需要实例化的属性
 6    public int number;
 7    public void mailCheck()
 8    {
 9       System.out.println("Mailing a check to " + name
10                            + " " + address);
11    }
12 }

序列化对象:该程序执行后,就创建了一个名为 employee.ser 文件

 1 import java.io.*;
 2  
 3 public class SerializeDemo
 4 {
 5    public static void main(String [] args)
 6    {
 7       Employee e = new Employee();
 8       e.name = "Reyan Ali";
 9       e.address = "Phokka Kuan, Ambehta Peer";
10       e.SSN = 11122333;
11       e.number = 101;
12       try
13       {
14          FileOutputStream fileOut =
15          new FileOutputStream("/tmp/employee.ser");
16          ObjectOutputStream out = new ObjectOutputStream(fileOut);
17          out.writeObject(e);
18          out.close();
19          fileOut.close();
20          System.out.printf("Serialized data is saved in /tmp/employee.ser");
21       }catch(IOException i)
22       {
23           i.printStackTrace();
24       }
25    }
26 }

反序列化:下面的 DeserializeDemo 程序实例了反序列化,/tmp/employee.ser 存储了 Employee 对象

 1 import java.io.*;
 2  
 3 public class DeserializeDemo
 4 {
 5    public static void main(String [] args)
 6    {
 7       Employee e = null;
 8       try
 9       {
10          FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
11          ObjectInputStream in = new ObjectInputStream(fileIn);
12          e = (Employee) in.readObject();
13          in.close();
14          fileIn.close();
15       }catch(IOException i)
16       {
17          i.printStackTrace();
18          return;
19       }catch(ClassNotFoundException c)
20       {
21          System.out.println("Employee class not found");
22          c.printStackTrace();
23          return;
24       }
25       System.out.println("Deserialized Employee...");
26       System.out.println("Name: " + e.name);
27       System.out.println("Address: " + e.address);
28       System.out.println("SSN: " + e.SSN);
29       System.out.println("Number: " + e.number);
30     }
31 }

执行结果:

Deserialized Employee...
Name: Reyan Ali
Address:Phokka Kuan, Ambehta Peer
SSN: 0
Number:101

当对象被序列化时,属性 SSN 的值为 111222333,但是因为该属性是短暂的,该值没有被发送到输出流。所以反序列化后 Employee 对象的 SSN 属性为 0。

原文地址:https://www.cnblogs.com/crazytrip/p/7125402.html