Java 的序列化設計極致體現了「簡單」哲學:只要類實現 java.io.Serializable 標記接口(無需實現任何方法),即可借助 ObjectOutputStream.writeObject() 與 ObjectInputStream.readObject() 輕鬆實現對象的持久化與還原。
下面的代碼演示了構造對象、序列化到文件、再反序列化還原並打印的全過程:
package Stream;
import java.io.*;
public class Serial implements Serializable {
int companyId;
String companyAddr;
boolean companyFlag;
public Serial() {} // 無參構造器(非必需)
public Serial(int companyId, String companyAddr, boolean companyFlag) {
this.companyId = companyId;
this.companyAddr = companyAddr;
this.companyFlag = companyFlag;
}
public static void main(String[] args) {
Serial serial1 = new Serial(752, "dayer street #5 building 02-287", false);
FileInputStream in = null;
FileOutputStream out = null;
ObjectInputStream oin = null;
ObjectOutputStream oout = null;
try {
out = new FileOutputStream("5.txt");
oout = new ObjectOutputStream(out);
serial1.serialize(oout); // 序列化
oout.close();
in = new FileInputStream("5.txt");
oin = new ObjectInputStream(in);
Serial serial2 = Serial.deserialize(oin); // 反序列化
System.out.println(serial2); // 打印結果
} catch (Exception ex) {
ex.printStackTrace();
} finally {
// 資源關閉邏輯省略...
}
}
/** 反序列化靜態工廠方法 */
public static Serial deserialize(ObjectInputStream oin) throws Exception {
return (Serial) oin.readObject();
}
@Override
public String toString() {
return "DATA: " + companyId + " " + companyAddr + " " + companyFlag;
}
/** 序列化實例方法 */
public void serialize(ObjectOutputStream oout) throws Exception {
oout.writeObject(this);
}
}
DATA: 752 dayer street #5 building 02-287 false
輸出與原始對象完全一致,驗證了默認序列化機制的正確性與易用性。
Serializable 無方法定義,僅作類型標識。ObjectOutputStream 輸出,ObjectInputStream 輸入。這個「感性認識」示例為深入理解序列化的版本控制、性能優化、安全防範等進階主題奠定了基礎。