This article from JavaTuturial

Java provides a mechanism, called object serialization where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent the object and its data can be used to recreate the object in memory.

Most impressive is that the entire process is JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different platform.

Classes ObjectInputStream and ObjectOutputStream are high-level streams that contain the methods for serializing and deserializing an object.

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:

    /**
* Write the specified object to the ObjectOutputStream. The class of the
* object, the signature of the class, and the values of the non-transient
* and non-static fields of the class and all of its supertypes are
* written. Default serialization for a class can be overridden using the
* writeObject and the readObject methods. Objects referenced by this
* object are written transitively so that a complete equivalent graph of
* objects can be reconstructed by an ObjectInputStream.
*
* <p>Exceptions are thrown for problems with the OutputStream and for
* classes that should not be serialized. All exceptions are fatal to the
* OutputStream, which is left in an indeterminate state, and it is up to
* the caller to ignore or recover the stream state.
*
* @throws InvalidClassException Something is wrong with a class used by
* serialization.
* @throws NotSerializableException Some object to be serialized does not
* implement the java.io.Serializable interface.
* @throws IOException Any exception thrown by the underlying
* OutputStream.
*/
public final void writeObject(Object obj) throws IOException {
if (enableOverride) {
writeObjectOverride(obj);
return;
}
try {
writeObject0(obj, false);
} catch (IOException ex) {
if (depth == 0) {
writeFatalException(ex);
}
throw ex;
}
}

The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:

  /**
* Read an object from the ObjectInputStream. The class of the object, the
* signature of the class, and the values of the non-transient and
* non-static fields of the class and all of its supertypes are read.
* Default deserializing for a class can be overriden using the writeObject
* and readObject methods. Objects referenced by this object are read
* transitively so that a complete equivalent graph of objects is
* reconstructed by readObject.
*
* <p>The root object is completely restored when all of its fields and the
* objects it references are completely restored. At this point the object
* validation callbacks are executed in order based on their registered
* priorities. The callbacks are registered by objects (in the readObject
* special methods) as they are individually restored.
*
* <p>Exceptions are thrown for problems with the InputStream and for
* classes that should not be deserialized. All exceptions are fatal to
* the InputStream and leave it in an indeterminate state; it is up to the
* caller to ignore or recover the stream state.
*
* @throws ClassNotFoundException Class of a serialized object cannot be
* found.
* @throws InvalidClassException Something is wrong with a class used by
* serialization.
* @throws StreamCorruptedException Control information in the
* stream is inconsistent.
* @throws OptionalDataException Primitive data was found in the
* stream instead of objects.
* @throws IOException Any of the usual Input/Output related exceptions.
*/
public final Object readObject()
throws IOException, ClassNotFoundException
{
if (enableOverride) {
return readObjectOverride();
} // if nested read, passHandle contains handle of enclosing object
int outerHandle = passHandle;
try {
Object obj = readObject0(false);
handles.markDependency(outerHandle, passHandle);
ClassNotFoundException ex = handles.lookupException(passHandle);
if (ex != null) {
throw ex;
}
if (depth == 0) {
vlist.doCallbacks();
}
return obj;
} finally {
passHandle = outerHandle;
if (closed && depth == 0) {
clear();
}
}
}

This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type.

To demonstrate how serialization works in Java, I am going to use the Employee class that we discussed early on in the book. Suppose that we have the following Employee class, which implements the Serializable interface:

class Employee implements java.io.Serializable{
public String name;
public String addr;
public transient int SSN;
public int num; public void mailCheck(){
System.out.println("Mailing a check to " + name + " " + addr);
}
}

Notice that for a class to be serialized successfully, two conditions must be met:

  • The class must implement the java.io.Serializable interface.

  • All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

    static void serializeEmployee(){
Employee e = new Employee();
e.name = "Reyan Ali";
e.addr = "Zpark, China";
e.SSN = 111222333;
e.num = 101; try{
FileOutputStream fileOut = new FileOutputStream("./employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser"); } catch (IOException i){
i.printStackTrace();
}
}

Deserializing an Object:

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:

   static void deserializeEmployee(){
Employee e = null; try {
FileInputStream inputFile = new FileInputStream("./employee.ser");
ObjectInputStream in = new ObjectInputStream(inputFile);
e = (Employee) in.readObject();
in.close();
inputFile.close();
e.mailCheck(); } catch (IOException i){
i.printStackTrace();
} catch (ClassNotFoundException c){
c.printStackTrace();
}
}

Here are following important points to be noted:

  • The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

  • Notice that the return value of readObject() is cast to an Employee reference.

  • The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.

The result and whole source code is here:

package serialization;

import java.io.*;

/**
* Created by *** on 1/3/16.
*/ class Employee implements java.io.Serializable{
public String name;
public String addr;
public transient int SSN;
public int num; public void mailCheck(){
System.out.println("Mailing a check to " + name + " " + addr);
}
} public class SerializeDemo { static void serializeEmployee(){
Employee e = new Employee();
e.name = "Reyan Ali";
e.addr = "Zpark, China";
e.SSN = 111222333;
e.num = 101; try{
FileOutputStream fileOut = new FileOutputStream("./employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in employee.ser"); } catch (IOException i){
i.printStackTrace();
}
} static void deserializeEmployee(){
Employee e = null; try {
FileInputStream inputFile = new FileInputStream("./employee.ser");
ObjectInputStream in = new ObjectInputStream(inputFile);
e = (Employee) in.readObject();
in.close();
inputFile.close();
e.mailCheck(); } catch (IOException i){
i.printStackTrace();
} catch (ClassNotFoundException c){
c.printStackTrace();
}
} public static void main(String[] args){
serializeEmployee();
deserializeEmployee();
}
}

Output of console:

Serialized data is saved in employee.ser
Mailing a check to Reyan Ali Zpark, China

java Serialization and Deserializaton的更多相关文章

  1. The Java serialization algorithm revealed---reference

    Serialization is the process of saving an object's state to a sequence of bytes; deserialization is ...

  2. JAVA Serialization 序列化

    最近在做Android 项目时用到了WebView,可悲的是,在html上有无数用户的操作,而这些操作被JS返回给了Android的内存中,当深层的Activity开启时,之前的Activity很可能 ...

  3. JAVA-基础(六) Java.serialization 序列化

    序 列 化 序列化(serialization)是把一个对象的状态写入一个字节流的过程. Serializable接口 只有一个实现Serializable接口的对象可以被序列化工具存储和恢复.Ser ...

  4. The Java Enum: A Singleton Pattern [reproduced]

    The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...

  5. Java transient关键字

    Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...

  6. java轻量级IOC框架Guice

    Google-Guice入门介绍(较为清晰的说明了流程):http://blog.csdn.net/derekjiang/article/details/7231490 使用Guice,需要添加第三方 ...

  7. Java内部类、静态嵌套类、局部内部类、匿名内部类

    Nested classes are further divided into two types: static nested classes: If the nested class is sta ...

  8. Java transient volatile关键字(转)

    Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...

  9. java volatile 和Transient 关键字

    java关键字volatile volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同 ...

随机推荐

  1. 达内TTS6.0课件oop_day01

  2. C++ Primer 读书笔记 第1章

    1.1 编写简单的C++程序 每个C++程序都必须包含一个main函数,因为main函数是系统执行入口,且main函数是唯一被系统显示调用的函数. 定义函数必须指定4个元素:返回类型.函数名.形参表. ...

  3. Sublime Text 3:3114的安装(目前最新),插件emmet的安装

    随便一些好了. 直接英文版吧,建议不要找中文版,学习英语不是? https://www.sublimetext.com/3   下载 https://github.com/wbond/package_ ...

  4. js 模拟java 中 的map

    //js模拟map Map = { obj : {}, put : function(key , value){ this.obj[key] = value; }, get : function(ke ...

  5. SQL serve创建与调用存储过程

    (1)创建 2编写存储过程(创建传参的存储过程)存储过程语法网络上很多不在累述 语法解析 Use Person 指定在那个数据库下建立存储过程 if (object_id('MyFunction', ...

  6. STL模板_概念

    模板和STL一.模板的背景知识1.针对不同的类型定义不同函数版本.2.借助参数宏摆脱类型的限制,同时也因为失去的类型检查而引 入风险.3.借助于编译预处理器根据函数宏框架,扩展为针对不同类型的 具体函 ...

  7. JavaScript 入門

    <html lang="en"> <head>   <meta charset="UTF-8">   <meta na ...

  8. 几本不错的开源书(to be continued)

    Linux 1.working-on-gnu-linux GNU/Linux 至今已經相當成熟並足以應付日常生活之使用,凍仁也於 2009 年開始使用它來工作至今,將藉由此書 1 來撰寫較有系統的文章 ...

  9. :last-child的诡异的问题!!

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  10. C++面试经常涉及的概念1

    1.new.delete.malloc.free关系 delete会调用对象的析构函数,和new对应.free只会释放内存,new调用构造函数.malloc与free是C++/C语言的标准库函数,ne ...