java Serialization and Deserializaton
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的更多相关文章
- The Java serialization algorithm revealed---reference
Serialization is the process of saving an object's state to a sequence of bytes; deserialization is ...
- JAVA Serialization 序列化
最近在做Android 项目时用到了WebView,可悲的是,在html上有无数用户的操作,而这些操作被JS返回给了Android的内存中,当深层的Activity开启时,之前的Activity很可能 ...
- JAVA-基础(六) Java.serialization 序列化
序 列 化 序列化(serialization)是把一个对象的状态写入一个字节流的过程. Serializable接口 只有一个实现Serializable接口的对象可以被序列化工具存储和恢复.Ser ...
- The Java Enum: A Singleton Pattern [reproduced]
The singleton pattern restricts the instantiation of a class to one object. In Java, to enforce this ...
- Java transient关键字
Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...
- java轻量级IOC框架Guice
Google-Guice入门介绍(较为清晰的说明了流程):http://blog.csdn.net/derekjiang/article/details/7231490 使用Guice,需要添加第三方 ...
- Java内部类、静态嵌套类、局部内部类、匿名内部类
Nested classes are further divided into two types: static nested classes: If the nested class is sta ...
- Java transient volatile关键字(转)
Volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同的线程总是看到某个成员变量的同一 ...
- java volatile 和Transient 关键字
java关键字volatile volatile修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同 ...
随机推荐
- leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume tha ...
- 最终有SpringMvc与Struts2的对照啦
眼下企业中使用SpringMvc的比例已经远远超过Struts2,那么两者究竟有什么差别,是非常多刚開始学习的人比較关注的问题,以下我们就来对SpringMvc和Struts2进行各方面的比較: 1. ...
- 1.对于.NET的初步理解和介绍
好久没写博客了,最近心情比较low,不知道为什么.很流行的一个问题叫做:如果你明天就挂了,那么你最后悔的事情将会是什么.我想了两个月,答案是不知道,无所谓.这样不好,那这个问题先放一边吧,我们开始这一 ...
- asp.net 使用my97 datepicker实现前后两个日期的范围界定
说明:日期选择后,前面的日期小于等后面的日期,后面的日期大于等于前面的日期.点点看就知道了:) - 这里将周末日期不可选.代码如下: <html xmlns="http://www.w ...
- 使用my97datepicker控件实现日期范围选择
注:(2014-12-05内容修改:添加运行效果) 使用my97datepicker 控件,需要对日期的范围进行控制,本人自己写了一个js完成此功能,示例为当前日期到下一周周五之间的日期可选,其他日期 ...
- 从零开始Unity3D游戏开发【1 常用快捷键】
Unity3D近两年起来的很快.自己对游戏一直很有兴趣,所以想找机会转游戏开发.目的之一是赚钱,目的之二是完成自己的小梦想. Unity3D的人才还是紧缺的,招聘网站上各个公司真敢拿着钱砸.让.NET ...
- 2014.9.16HTML表单CSS
(一)表格 合并单元格(少用) (合并列) 1.先选中要合并的2个或多个单元格,然后点击以下图标 代码:<td colspan="2"> </td> 2.设 ...
- C学习之指针强化
char *p = (char *)malloc(100); malloc是用于分配内存的函数,它的参数为int型,表示分配多少个字节长度,其返回类型为void*,在这里用char*就是强制转化,指定 ...
- Notes常用事件整理
① ボタンのクリック事件: Sub Click(Source As Button) Dim ws As New NotesUIWorkspace Dim uidoc As NotesUIDo ...
- jquery.validate 一些技巧
1.Validator.element() Validates a single element, returns true if it is valid, false otherwise. http ...