在 Java 中,你可以通過實現 java.io.Serializable
接口來自定義序列化機制
Serializable
接口:import java.io.Serializable;
public class CustomObject implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public CustomObject(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 方法
}
這里,我們創建了一個名為 CustomObject
的類,并實現了 Serializable
接口。同時,我們定義了一個 serialVersionUID
字段,它是用于序列化版本控制的。
為了自定義序列化和反序列化過程,我們需要實現 java.io.Externalizable
接口,該接口擴展了 Serializable
接口并添加了兩個方法:writeExternal(ObjectOutput out)
和 readExternal(ObjectInput in)
。
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class CustomObject implements Externalizable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
public CustomObject(String name, int age) {
this.name = name;
this.age = age;
}
// getter 和 setter 方法
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(name);
out.writeInt(age);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
name = in.readUTF();
age = in.readInt();
}
}
在上面的示例中,我們實現了 writeExternal
和 readExternal
方法,以便在序列化和反序列化過程中使用自定義邏輯。
ObjectOutputStream
和 ObjectInputStream
進行序列化和反序列化:現在我們可以使用 ObjectOutputStream
和 ObjectInputStream
對 CustomObject
實例進行序列化和反序列化。
import java.io.*;
public class CustomSerializationExample {
public static void main(String[] args) {
CustomObject obj = new CustomObject("John Doe", 30);
try {
// 序列化
FileOutputStream fileOut = new FileOutputStream("customObject.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(obj);
out.close();
fileOut.close();
System.out.printf("Serialized data is saved in customObject.ser");
// 反序列化
FileInputStream fileIn = new FileInputStream("customObject.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
CustomObject deserializedObj = (CustomObject) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized object...");
System.out.println("Name: " + deserializedObj.getName());
System.out.println("Age: " + deserializedObj.getAge());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
在上面的示例中,我們首先創建了一個 CustomObject
實例,然后使用 ObjectOutputStream
將其序列化到文件 customObject.ser
中。接下來,我們使用 ObjectInputStream
從文件中反序列化對象,并將其轉換回 CustomObject
類型。最后,我們打印出反序列化對象的屬性值。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。