Java序列化是指將對象轉換為字節(jié)序列的過程,以便在網(wǎng)絡上傳輸或將其存儲在磁盤上。序列化后的對象可以在需要時通過反序列化重新恢復成原來的對象。Java序列化可以使用Java IO類庫中的ObjectInputStream和ObjectOutputStream來實現(xiàn)。
/** * Java序列化示例 */ public class SerializeDemo implements Serializable { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public class Main { public static void main(String[] args) { SerializeDemo sd = new SerializeDemo(); sd.setName("Alice"); sd.setAge(25); try { FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(sd); out.close(); fileOut.close(); System.out.println("Serialized data is saved in employee.ser"); } catch (IOException i) { i.printStackTrace(); } } }
范序列化是Java 5引入的新特性,它允許將通用類型的對象序列化成字節(jié)序列,這些類型可以是任意類型(包括集合類型和數(shù)組類型)。范序列化通過Java 5中的新接口和特殊注釋來實現(xiàn),它包括ParameterizedType、TypeVariable、GenericArrayType等接口。
/** * Java范序列化示例 */ import java.lang.reflect.*; import java.io.*; class Boximplements Serializable { private T t; public void set(T t) { this.t = t; } public T get() { return t; } public static void main(String[] args) { Box integerBox = new Box (); integerBox.set(Integer.valueOf(10)); Class>clazz = integerBox.getClass(); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(integerBox); ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); Box newBox = (Box )ois.readObject(); System.out.println(newBox.get()); } catch(Exception e) { e.printStackTrace(); } } }