在Java中,要對類變量進行序列化,需要遵循以下步驟:
java.io.Serializable
接口。這個接口是一個標記接口,沒有任何方法需要實現。實現此接口的目的是告訴Java虛擬機(JVM)這個類的對象可以被序列化。import java.io.Serializable;
public class MyClass implements Serializable {
// 類的其他成員和方法
}
public class MyClass implements Serializable {
private int id;
private String name;
private transient int password; // 不會被序列化的變量
// 類的其他成員和方法
}
在這個例子中,id
和name
將被序列化,而password
變量被標記為transient
,因此它不會被序列化。
java.io.ObjectOutputStream
類將對象序列化為字節流。首先,需要創建一個ObjectOutputStream
對象,然后使用它的writeObject
方法將對象寫入輸出流。import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializeExample {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.setId(1);
obj.setName("John Doe");
obj.setPassword("secret");
try {
FileOutputStream fileOut = new FileOutputStream("myObject.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in myObject.ser");
} catch (Exception e) {
e.printStackTrace();
}
}
}
這段代碼將MyClass
對象序列化為名為myObject.ser
的文件。
java.io.ObjectInputStream
類。首先,需要創建一個ObjectInputStream
對象,然后使用它的readObject
方法從輸入流中讀取對象。import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeExample {
public static void main(String[] args) {
MyClass deserializedObj = null;
try {
FileInputStream fileIn = new FileInputStream("myObject.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
deserializedObj = (MyClass) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
return;
}
System.out.println("Deserialized object:");
System.out.println("ID: " + deserializedObj.getId());
System.out.println("Name: " + deserializedObj.getName());
System.out.println("Password: " + deserializedObj.getPassword());
}
}
這段代碼將從myObject.ser
文件中讀取序列化的對象,并將其反序列化為MyClass
類型的實例。注意,由于password
變量被標記為transient
,因此在反序列化后,它的值將為默認值(對于整數類型為0)。