在Java中序列化物件時,靜態變數的值是否會被儲存?
在Java中,序列化是一個可以將物件的狀態寫入位元組流的概念,以便我們可以透過網路傳輸它(使用JPA和RMI等技術)。
要序列化一個物件:
- 確保類實現了Serializable介面。
- 建立一個表示要將物件儲存到的檔案的**FileOutputStream**物件(抽象路徑)。
- 透過傳遞上面建立的**FileOutputStream**物件來建立一個ObjectOutputStream物件。
- 使用writeObject()方法將物件寫入檔案。
要反序列化一個物件:
- 建立一個表示包含序列化物件的**FileInputStream**物件。
- 使用readObject()方法從檔案中讀取物件。
- 使用檢索到的物件。
反序列化物件中的變數
當我們反序列化一個物件時,只有例項變數會被儲存,並且在處理後將具有相同的值。
瞬態變數 - 瞬態變數的值永遠不會被考慮(它們被排除在序列化過程之外)。也就是說,當我們宣告一個變數為瞬態變數時,反序列化後的值將始終為null、false或零(預設值)。
靜態變數 - 靜態變數的值在反序列化過程中不會被保留。事實上,靜態變數也不會被序列化,但由於它們屬於類。反序列化後,它們會從類中獲取它們當前的值。
示例
在這個程式中,我們在反序列化類之前更改了類的例項、靜態和瞬態變數的值。
處理之後,例項變數的值將相同。瞬態變數顯示預設值,靜態變數顯示來自類的新的(當前)值。
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