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修饰的成员变量在每次被线程访问时,都强迫从主内存中重读该成员变量的值.而且,当成员变量发生变化时,强迫线程将变化值回写到主内存.这样在任何时刻,两个不同 ...
随机推荐
- iOS_词典阵列 按key分组和排序
// // main.m // SortGroup // // Created by beyond on 14-10-26. // Copyright (c) 2014年 beyond.com All ...
- Asp.net 获取图片列表并打包下载
先引用:ICSharpCode.SharpZipLib.dll 后台代码: using System.IO; using ICSharpCode.SharpZipLib.Zip; using ICSh ...
- 列求key出现的频率
1 cat mc.log | grep LOGIN_GET | awk '{print $9}' | sort | uniq -c
- yii2.0 控制器方法 视图表单 Form表单处理
假设我们在ArticleController.php下面的actionForm方法中来处理提交的表单 新建立一个 views/Article/article-form.php文件用来作为输入表单 &l ...
- 【转】Centos 设置IP地址的几种方式
对于很多刚刚接触linux的朋友来说,如何设置linux系统的IP地址,作为第一步,下面小编以centos系统为例,给大家演示如何给centos设置IP地址,如何修改linux 系统IP地址? 查看I ...
- eclipse更改主题
长期使用eclipse,导致视觉疲劳,就想着能否换个主题调节调节. 通过设置window>preferences>appearance设置theme,貌似不起作用. 一查,发现一个绝佳的网 ...
- 解决:sudo: parse error in /etc/sudoers near line 24 ...报错
ubuntu系统下由于添加用户权限的时候直接用的vim对 /etc/sudoers 文件编辑,保存退出的时候,再使用sudo su 等等命令一直报错如下: sudo: parse error in / ...
- Web存储(Web Storage)介绍
Web存储即在客户端存储数据. 在没有Web Storage之前,是通过cookie来在客户端存储数据的.但是由于 浏览器能存cookie数比较少.如IE8,Firefox,opera每个域可以保存的 ...
- DateTimePicker——开源的Android日历类库
Github托管地址:https://github.com/flavienlaurent/datetimepicker
- 解决libc.so.6: version `GLIBC_2.14' not found问题, 升级glibc,glibc-2.15
0.以下在系统CentOS 6.3 x86_64上操作 1.试图运行程序,提示"libc.so.6: version `GLIBC_2.14' not found",原因是系统的g ...