🐵 #面试 #CCQC
可序列化(adj.Serializable)
- 定义:序列化指:
- 将java对象转换成可保持(为文件)或者可传输(网络)的格式。
- 相对应的,反序列化即将上面的流转为的对象。
- 为什么要序列化?
- 需要将对象进行网络传输。
- 需要将对象进行持久保存,但不用数据库。
- Serializable接口:
- 标识这个类的对象可序列化
实例:
参与序列化的对象
public class Employee implements java.io.Serializable{public int number;public void mailCheck(){System.out.println("Mailing a check to " + name + " " + address);}}
- ⭐可序列化的类必须实现
java.io.Serializable接口。 - 类的属性必须是可序列化的。如果属性不能序列化,应当注明。
序列化:
import java.io.*;public class SerializeDemo{public static void main(String [] args){e.number = 101;try{FileOutputStream fileOut = new FileOutputStream("/tmp/employee.ser"); //指定序列化保存文件ObjectOutputStream out = new ObjectOutputStream(fileOut); //序列化out.writeObject(e);out.close();fileOut.close();}catch(IOException i){i.printStackTrace();}}}
反序列化: ```java import java.io.*;
public class DeserializeDemo { public static void main(String [] args) { Employee e = null; try { FileInputStream fileIn = new FileInputStream(“/tmp/employee.ser”); //打开序列对象的文件 ObjectInputStream in = new ObjectInputStream(fileIn); //准备反序列化 e = (Employee) in.readObject(); //赋予对象 in.close(); fileIn.close(); }catch(IOException i) { i.printStackTrace(); return; }catch(ClassNotFoundException c) { System.out.println(“Employee class not found”); c.printStackTrace(); return; } System.out.println(“Number: “ + e.number); } } ```
