在Java中,對象序列化指的是將對象用字節序列的形式表示,這些字節序列包含了對象的數據和信息,一個序列化後的對象可以被寫到數據庫或文件中,並且支持從數據庫或文件中反序列化,從而在內存中重建對象;
序列化經常被用於對象的網絡傳輸或本地存儲。網絡基礎設施和硬盤只能識別位和字節信息,而不能識別Java對象。通過序列化能將Java對象轉成字節形式,從而在網絡上傳輸或存儲在硬盤。
那麼為什麼我們需要存儲或傳輸對象呢?根據我的編程經驗,有如下原因需要將對象序列化(以下原因,我表示沒使用過。。。):
順便也說下,根據我(真正的我)的編程經驗,序列化使用情況如下:
以下代碼展示了如何讓一個類可序列化,對象的序列化以及反序列化;
對象:
package serialization;
import java.io.Serializable;
public class Dog implements Serializable {
private static final long serialVersionUID = -5742822984616863149L;
private String name;
private String color;
private transient int weight;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public void introduce() {
System.out.println("I have a " + color + " " + name + ".");
}
}
main方法
package serialization;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeDemo {
public static void main(String[] args) {
// create an object
Dog e = new Dog();
e.setName("bulldog");
e.setColor("white");
e.setWeight(5);
// serialize
try {
FileOutputStream fileOut = new FileOutputStream("./dog.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.printf("Serialized dog is saved in ./dog.ser");
} catch (IOException i) {
i.printStackTrace();
}
e = null;
// Deserialize
try {
FileInputStream fileIn = new FileInputStream("./dog.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Dog) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Dog class not found");
c.printStackTrace();
return;
}
System.out.println("\nDeserialized Dog ...");
System.out.println("Name: " + e.getName());
System.out.println("Color: " + e.getColor());
System.out.println("Weight: " + e.getWeight());
e.introduce();
}
}
結果打印: