【译】Java中的对象序列化
生活随笔
收集整理的這篇文章主要介紹了
【译】Java中的对象序列化
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
好久沒翻譯simple java了,睡前來一篇。
譯文鏈接:
http://www.programcreek.com/2014/01/java-serialization/
什么是對象序列化
在Java中,對象序列化指的是將對象用字節序列的形式表示,這些字節序列包含了對象的數據和信息,一個序列化后的對象可以被寫到數據庫或文件中,并且支持從數據庫或文件中反序列化,從而在內存中重建對象;
為什么需要序列化
序列化經常被用于對象的網絡傳輸或本地存儲。網絡基礎設施和硬盤只能識別位和字節信息,而不能識別Java對象。通過序列化能將Java對象轉成字節形式,從而在網絡上傳輸或存儲在硬盤。
那么為什么我們需要存儲或傳輸對象呢?根據我的編程經驗,有如下原因需要將對象序列化(以下原因,我表示沒使用過。。。):
- 一個對象的創建依賴很多上下文環境,一旦被創建,它的方法和屬性會被很多其它組件所使用;
- 一個包含了很多屬性的對象創建后,我們并不清楚如何使用這些屬性,所以將它們存儲到數據庫用于后續的數據分析;
順便也說下,根據我(真正的我)的編程經驗,序列化使用情況如下:
- 網絡上的對象傳輸
- 使用一些緩存框架的時候,比如ehcache,將對象緩存到硬盤的時候,需要序列化,還有hibernate也會用到;
- RMI(遠程方法調用)
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 objectDog e = new Dog();e.setName("bulldog");e.setColor("white");e.setWeight(5);// serializetry {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;// Deserializetry {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();} }結果打印:
Serialized dog is saved in ./dog.ser
Deserialized Dog ...
Name: bulldog
Color: white
Weight: 0
I have a white bulldog.
本文轉自風一樣的碼農博客園博客,原文鏈接:http://www.cnblogs.com/chenpi/p/5582492.html,如需轉載請自行聯系原作者總結
以上是生活随笔為你收集整理的【译】Java中的对象序列化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 订单自动生成器的算法研究与实现
- 下一篇: Java 添加播放MIDI音乐