在Java中,序列化(Serialization)是將對象轉換為字節(jié)流的過程,而反序列化(Deserialization)是將字節(jié)流轉換為對象的過程。序列化與反序列化主要用于對象的持久化存儲或對象在網(wǎng)絡中的傳輸。
Serializable
接口,這是一個標記接口,沒有任何方法需要實現(xiàn)。import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
// Constructors, getters and setters
}
ObjectOutputStream
類來實現(xiàn)序列化,將對象寫入輸出流中。import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializationExample {
public static void main(String[] args) {
Person person = new Person("Alice", 30);
try (FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(person);
System.out.println("Object has been serialized");
} catch (Exception e) {
e.printStackTrace();
}
}
}
ObjectInputStream
類來實現(xiàn)反序列化,從輸入流中讀取對象。import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializationExample {
public static void main(String[] args) {
try (FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn)) {
Person person = (Person) in.readObject();
System.out.println("Object has been deserialized");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static final long serialVersionUID
進行控制。InvalidClassException
異常,所以在進行序列化和反序列化時要謹慎處理版本兼容性問題。以上是序列化與反序列化的基礎教程,希望能幫助你了解如何在Java中進行對象的持久化存儲與傳輸。