在 Java 中反序列化物件時,是否會呼叫物件的建構函式?
在 Java 中,序列化是一個可以將物件的狀態寫入位元組流的概念,以便我們可以透過網路傳輸它(使用 JPA 和 RMI 等技術)。
要序列化一個物件:
- 確保該類實現了 Serializable 介面。
- 建立一個 **FileOutputStream** 物件,表示要將物件儲存到的檔案的路徑。
- 透過傳遞上面建立的 **FileOutputStream** 物件來建立一個 ObjectOutputStream 物件。
- 使用 writeObject() 方法將物件寫入檔案。
要反序列化一個物件:
- 建立一個 **FileInputStream** 物件,表示包含序列化物件的的檔案。
- 使用 readObject() 方法從檔案中讀取物件。
- 使用檢索到的物件。
**建構函式**類似於方法,在建立類的物件時呼叫,通常用於初始化類的例項變數。建構函式與它們的類名相同,並且沒有返回型別。
如果您不提供建構函式,編譯器會代表您定義一個,該建構函式會將例項變數初始化為預設值。
建構函式和反序列化
當我們反序列化一個物件時,永遠不會呼叫其類的建構函式。考慮下面的例子,這裡我們有一個名為 student 的類,它有兩個例項變數和一個預設建構函式(用兩個硬編碼值初始化)和一個引數化建構函式。
此類的 display() 方法顯示當前例項的變數值。
我們透過傳遞兩個值(vani 和 27)來建立 Student 類的物件並將其序列化。
當我們反序列化此物件並呼叫 display() 方法時,將列印我們傳遞的值。靜態變數將列印來自類的新的(當前的)值。
示例
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Student implements Serializable{
private String name;
private transient int age;
private static int year = 2018;
public Student(){
System.out.println("This is a constructor");
this.name = "Krishna";
this.age = 25;
}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public void display() {
System.out.println("Name: "+this.name);
System.out.println("Age: "+this.age);
System.out.println("Year: "+Student.year);
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setYear(int year) {
Student.year = year;
}
}
public class SerializeExample{
public static void main(String args[]) throws Exception{
//Creating a Student object
Student std = new Student("Vani", 27);
//Serializing the object
FileOutputStream fos = new FileOutputStream("e:\student.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(std);
oos.close();
fos.close();
//Printing the data before de-serialization
System.out.println("Values before de-serialization");
std.display();
//Changing the static variable value
std.setYear(2019);
//Changing the instance variable value
std.setName("Varada");
//Changing the transient variable value
std.setAge(19);
System.out.println("Object serialized.......");
//De-serializing the object
FileInputStream fis = new FileInputStream("e:\student.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Student deSerializedStd = (Student) ois.readObject();
System.out.println("Object de-serialized.......");
ois.close();
fis.close();
System.out.println("Values after de-serialization");
deSerializedStd.display();
}
}輸出
Values before de-serialization: Name: Vani Age: 27 Year: 2018 Object serialized....... Object de-serialized....... Values after de-serialization: Name: Vani Age: 0 Year: 2019
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP