Java序列化和反序列化是一種用于將Java對象轉換為字節流以便存儲或傳輸的方法。當一個對象被序列化時,它的狀態被寫入到一個字節流中,以便可以在稍后的時間重新創建對象。反序列化是將字節流轉換回對象狀態的過程。 Java序列化和反序列化廣泛用于網絡通信、緩存、持久化等領域。
public class Student implements Serializable { private String name; private int age; private String address; private transient String password; // get and set methods } public class SerializationDemo { public static void main(String[] args) { Student student = new Student(); student.setName("Lucy"); student.setAge(18); student.setAddress("Beijing"); student.setPassword("123456"); // serialization try { FileOutputStream fileOut = new FileOutputStream("student.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(student); out.close(); fileOut.close(); System.out.println("Serialized data is saved in student.ser"); } catch (IOException e) { e.printStackTrace(); } // deserialization try { FileInputStream fileIn = new FileInputStream("student.ser"); ObjectInputStream in = new ObjectInputStream(fileIn); Student s = (Student) in.readObject(); in.close(); fileIn.close(); System.out.println("Name: " + s.getName()); System.out.println("Age: " + s.getAge()); System.out.println("Address: " + s.getAddress()); // password will be null because it is marked as transient System.out.println("Password: " + s.getPassword()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
在上面的代碼中,我們定義了一個Student類,并實現了Serializable接口以便將對象序列化。在序列化過程中,我們將Student對象寫入到一個文件中。在反序列化過程中,我們從該文件中讀取數據并將其轉換為Student對象。在輸出Student對象的屬性時,我們發現transient關鍵字標記的password屬性不會被反序列化。