When---什么时候需要序列化和反序列化:

简单的写一个hello world程序,用不到序列化和反序列化。写一个排序算法也用不到序列化和反序列化。但是当你想要将一个对象进行持久化写入文件,或者你想将一个对象从一个网络地址通过网络协议发送到另一个网络地址时,这时候就需要考虑序列化和反序列化了。另外如果你想对一个对象实例进行深度拷贝,也可以通过序列化和反序列化的方式进行。

What---什么是序列化和反序列化:

Serialization-序列化:可以看做是将一个对象转化为二进制流的过程

Deserialization-反序列化:可以看做是将对象的二进制流重新读取转换成对象的过程

How---怎么实现序列化:

只有实现了 Serializable 或 Externalizable 接口的类的对象才能被序列化,否则抛出异常。
对于实现了这两个接口,具体序列化和反序列化的过程又分以下3中情况:
情况1:若类仅仅实现了Serializable接口,则可以按照以下方式进行序列化和反序列化
ObjectOutputStream采用默认的序列化方式,对对象的非transient的实例变量进行序列化。
ObjcetInputStream采用默认的反序列化方式,对对象的非transient的实例变量进行反序列化。

情况2:若类不仅实现了Serializable接口,并且还定义了readObject(ObjectInputStream in)和writeObject(ObjectOutputSteam out),则采用以下方式进行序列化与反序列化。
ObjectOutputStream调用对象的writeObject(ObjectOutputStream out)的方法进行序列化。
ObjectInputStream会调用对象的readObject(ObjectInputStream in)的方法进行反序列化。

情况3:若类实现了Externalnalizable接口,且类必须实现readExternal(ObjectInput in)和writeExternal(ObjectOutput out)方法,则按照以下方式进行序列化与反序列化。
ObjectOutputStream调用对象的writeExternal(ObjectOutput out))的方法进行序列化。
ObjectInputStream会调用对象的readExternal(ObjectInput in)的方法进行反序列化。

为了进一步说明,我们直接看jdk底层ArrayList的序列化和反序列化:

 // 实现了Serializable接口,可以被序列化
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L; /**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
// 实际元素被transient修饰,默认不会进行序列化
private transient Object[] elementData; ..... /**
* Save the state of the <tt>ArrayList</tt> instance to a stream (that
* is, serialize it).
*
* @serialData The length of the array backing the <tt>ArrayList</tt>
* instance is emitted (int), followed by all of its elements
* (each an <tt>Object</tt>) in the proper order.
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject(); // Write out array length
s.writeInt(elementData.length); // Write out all elements in the proper order.
for (int i=0; i<size; i++)
s.writeObject(elementData[i]); if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
} } /**
* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
* deserialize it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in size, and any hidden stuff
s.defaultReadObject(); // Read in array length and allocate array
int arrayLength = s.readInt();
Object[] a = elementData = new Object[arrayLength]; // Read in all elements in the proper order.
for (int i=0; i<size; i++)
a[i] = s.readObject();
}
}

可以看到,初看之下ArrayList的实际存储元素不能被序列化。但实际上根据我们上面的第二条原则,知道因为其重写了writeObject和readObject方法,而在方法的内部实现了对具体存储对象的序列化与反序列化。那么这两个方法究竟是在什么时候执行的呢?我们需要转到ObjectOutputStream这个对象上来:

 /**
* Serialization's descriptor for classes. It contains the name and
* serialVersionUID of the class. The ObjectStreamClass for a specific class
* loaded in this Java VM can be found/created using the lookup method. */
// 在序列化对象之前会封装一个ObjectStreamClass对象
public class ObjectStreamClass implements Serializable {
/** class-defined writeObject method, or null if none */
private Method writeObjectMethod; /**
* Creates local class descriptor representing given class.
*/
private ObjectStreamClass(final Class cl) {   
      ......
if (serializable) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
if (isEnum) {
suid = Long.valueOf(0);
fields = NO_FIELDS;
return null;
}
if (cl.isArray()) {
fields = NO_FIELDS;
return null;
} suid = getDeclaredSUID(cl);
try {
fields = getSerialFields(cl);
computeFieldOffsets();
} catch (InvalidClassException e) {
serializeEx = deserializeEx = e;
fields = NO_FIELDS;
} if (externalizable) {
cons = getExternalizableConstructor(cl);
} else {
cons = getSerializableConstructor(cl);
// 其实就是writeObject方法
writeObjectMethod = getPrivateMethod(cl, "writeObject",
65 new Class[] { ObjectOutputStream.class },
66 Void.TYPE);
readObjectMethod = getPrivateMethod(cl, "readObject",
new Class[] { ObjectInputStream.class },
Void.TYPE);
readObjectNoDataMethod = getPrivateMethod(
cl, "readObjectNoData", null, Void.TYPE);
hasWriteObjectData = (writeObjectMethod != null);
}
writeReplaceMethod = getInheritableMethod(
cl, "writeReplace", null, Object.class);
readResolveMethod = getInheritableMethod(
cl, "readResolve", null, Object.class);
return null;
}
});
} else {
suid = Long.valueOf(0);
fields = NO_FIELDS;
}   ....... } /**
* Returns non-static private method with given signature defined by given
* class, or null if none found. Access checks are disabled on the
* returned method (if any).
*/
private static Method getPrivateMethod(Class cl, String name,
Class[] argTypes,
Class returnType)
{
try {
Method meth = cl.getDeclaredMethod(name, argTypes);
meth.setAccessible(true);
int mods = meth.getModifiers();
return ((meth.getReturnType() == returnType) &&
((mods & Modifier.STATIC) == 0) &&
((mods & Modifier.PRIVATE) != 0)) ? meth : null;
} catch (NoSuchMethodException ex) {
return null;
}
} /**
* Returns true if represented class is serializable (but not
* externalizable) and defines a conformant writeObject method. Otherwise,
* returns false.
*/
boolean hasWriteObjectMethod() {
return (writeObjectMethod != null);
}
} public class ObjectOutputStream
extends OutputStream implements ObjectOutput, ObjectStreamConstants
{
/**
* Magic number that is written to the stream header.
*/
final static short STREAM_MAGIC = (short)0xaced; /**
* Version number that is written to the stream header.
*/
final static short STREAM_VERSION = 5; public ObjectOutputStream(OutputStream out) throws IOException {
verifySubclass();
bout = new BlockDataOutputStream(out);
handles = new HandleTable(10, (float) 3.00);
subs = new ReplaceTable(10, (float) 3.00);
enableOverride = false;
// 写入头信息
writeStreamHeader();
bout.setBlockDataMode(true);
if (extendedDebugInfo) {
debugInfoStack = new DebugTraceInfoStack();
} else {
debugInfoStack = null;
}
} protected void writeStreamHeader() throws IOException {
bout.writeShort(STREAM_MAGIC);
bout.writeShort(STREAM_VERSION);
} /**
* 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. */
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;
}
} /**
* Underlying writeObject/writeUnshared implementation.
*/
private void writeObject0(Object obj, boolean unshared)
throws IOException
{
boolean oldMode = bout.setBlockDataMode(false);
depth++;
try {
// handle previously written and non-replaceable objects
  ......
// check for replacement object
......
// if object replaced, run through original checks a second time
  ......
// remaining cases
if (obj instanceof String) {
writeString((String) obj, unshared);
} else if (cl.isArray()) {
writeArray(obj, desc, unshared);
} else if (obj instanceof Enum) {
writeEnum((Enum) obj, desc, unshared);
} else if (obj instanceof Serializable) {
// 如果不是特殊对象类型,最终会调用该方法
writeOrdinaryObject(obj, desc, unshared);
} else {
if (extendedDebugInfo) {
throw new NotSerializableException(
cl.getName() + "\n" + debugInfoStack.toString());
} else {
throw new NotSerializableException(cl.getName());
}
}
} finally {
depth--;
bout.setBlockDataMode(oldMode);
}
} private void writeOrdinaryObject(Object obj,
ObjectStreamClass desc,
boolean unshared)
throws IOException
{
if (extendedDebugInfo) {
debugInfoStack.push(
(depth == 1 ? "root " : "") + "object (class \"" +
obj.getClass().getName() + "\", " + obj.toString() + ")");
}
try {
desc.checkSerialize(); bout.writeByte(TC_OBJECT);
writeClassDesc(desc, false);
handles.assign(unshared ? null : obj);
if (desc.isExternalizable() && !desc.isProxy()) {
writeExternalData((Externalizable) obj);
} else {
// 一般情况下会调用该方法
writeSerialData(obj, desc);
}
} finally {
if (extendedDebugInfo) {
debugInfoStack.pop();
}
}
}   /**
* Writes instance data for each serializable class of given object, from
* superclass to subclass.
*/
private void writeSerialData(Object obj, ObjectStreamClass desc)
throws IOException
{
ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
for (int i = 0; i < slots.length; i++) {
ObjectStreamClass slotDesc = slots[i].desc;
// 如果重写了序列化的方法writeObject,则调用对应的方法进行写入,其实就是ObjectStreamClass 中的对应方法,可以得出序列化的第2条规则
if (slotDesc.hasWriteObjectMethod()) {
PutFieldImpl oldPut = curPut;
curPut = null; if (extendedDebugInfo) {
debugInfoStack.push(
"custom writeObject data (class \"" +
slotDesc.getName() + "\")");
} SerialCallbackContext oldContext = curContext;
try {
curContext = new SerialCallbackContext(obj, slotDesc); bout.setBlockDataMode(true);
slotDesc.invokeWriteObject(obj, this);
bout.setBlockDataMode(false);
bout.writeByte(TC_ENDBLOCKDATA);
} finally {
curContext.setUsed();
curContext = oldContext; if (extendedDebugInfo) {
debugInfoStack.pop();
}
} curPut = oldPut;
} else {
// 未重写调用默认的方法
defaultWriteFields(obj, slotDesc);
}
}
}

以上代码就是分析序列化情况2的实现,反序列化也可以同样跟踪发现,这里不再重复。

Deeper---其他序列化反序列化的深入问题:

a. 被transient和static修饰的成员变量不会被序列化

b. 有个需要注意的点来自 Serializable 接口的说明文档,简单说明如下:

假设A实现了Serializable接口,且A为B的子类,B没有实现Serializable接口。那么在序列化和反序列话的时候,B的无参构造函数负责B的相关属性的序列化和反序列化。特殊的,当B没有无参构造函数的时候,将A对象进行序列化时不会报错,但是反序列化获取A的时候报错。

 static class SubSerializableTest extends SerializableTest implements Serializable {
private static final long serialVersionUID = 1L; private String subName; public SubSerializableTest(String name, String subName) {
super(name, 18);
this.subName = subName;
} public String getSubName() {
return subName;
}
} static class SerializableTest { public SerializableTest() {
this.name = "aaa";
this.age = 21;
} public SerializableTest(String name, int age) {
this.name = name;
} private String name; private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
} SubSerializableTest subTest = new SubSerializableTest("KiDe", "KiDe");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("e:/1.txt")));
oos.writeObject(subTest);
oos.close(); ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("e:/1.txt")));
subTest = (SubSerializableTest) ois.readObject(); // 如果SerializableTest未实现无参的构造函数,则抛出 Exception in thread "main" java.io.InvalidClassException: test.Test$SubSerializableTest; test.Test$SubSerializableTest; no valid constructor
System.out.println(subTest.getName()); // aaa
System.out.println(subTest.getSubName()); // KiDe
ois.close();

另外多说一句,假设B是A的一个属性但是B没有实现 Serializable 接口,这时候不管序列化还是反序列化A都会报异常:
Exception in thread "main" java.io.NotSerializableException: test.Test$SerializableTest。

c. 由于上面所讲的限制,就存在需要特殊处理未实现 Serializable 接口的属性,这时候可以重写下面三个方法:
private void writeObject(java.io.ObjectOutputStream out) throws IOException
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
private void readObjectNoData() throws ObjectStreamException;

前面两个方法主要用来序列化和反序列化被transient或者static修饰的属性,将其写入流:

 private void writeObject(ObjectOutputStream out) throws IOException {
System.out.println("writeOject");
out.defaultWriteObject();
out.writeInt(123);
} private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
System.out.println("readOject");
in.defaultReadObject();
System.out.println(in.readInt());;
}

第三个方法属于一种防御性方法,一般不会用到,官方解释是;
The readObjectNoData method is responsible for initializing the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.

这里暂时没有试验出这个方法的使用场景,略过。

d.  还有两个方法在序列化和反序列化的时候会被自动调用到:

ANY-ACCESS-MODIFIER Object writeReplace() throws ObjectStreamException;
ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException;

其中writeReplace调用在writeObject之前,可以修改对象属性,最终返回this,readResolve调用在readObject之后,可以修改读取到的对象的属性,返回this

一般的应用是在单例模式中,重写readResoive方法,返回单例。防止通过序列化和反序列化导致单例模式生效的问题。

java序列化反序列化深入探究的更多相关文章

  1. java序列化反序列化深入探究(转)

    When---什么时候需要序列化和反序列化: 简单的写一个hello world程序,用不到序列化和反序列化.写一个排序算法也用不到序列化和反序列化.但是当你想要将一个对象进行持久化写入文件,或者你想 ...

  2. 初尝Java序列化/反序列化对象

    看个类: package com.wjy.bytes; import java.io.Serializable; public class ObjTest implements Serializabl ...

  3. java序列化/反序列化之xstream、protobuf、protostuff 的比较与使用例子

    目录 背景 测试 环境 工具 说明 结果 结论 xstream简单教程 准备 代码 protobuf简单教程 快速入门 下载.exe编译器 编写.proto文件 利用编译器编译.proto文件生成ja ...

  4. Java序列化反序列化对象流ObjectInputStream、ObjectOutputStream

    使用Person类作为Object进行示范 注意:Object要能被写入流需要实现Serializable接口 存储的文件后缀名为.ser 示范Person类 import java.io.Seria ...

  5. Java——序列化 反序列化

    记录一下: 先粘两个比较繁琐的方法: put: public void putSerializableObject(String key, Object value, int expireTime) ...

  6. Java 序列化 反序列化 历史版本处理

    直接引用  http://www.cnblogs.com/xdp-gacl/p/3777987.html

  7. Java基础18:Java序列化与反序列化

    更多内容请关注微信公众号[Java技术江湖] 这是一位阿里 Java 工程师的技术小站,作者黄小斜,专注 Java 相关技术:SSM.SpringBoot.MySQL.分布式.中间件.集群.Linux ...

  8. Java 序列化与反序列化

    1.什么是序列化?为什么要序列化? Java 序列化就是指将对象转换为字节序列的过程,而反序列化则是只将字节序列转换成目标对象的过程. 我们都知道,在进行浏览器访问的时候,我们看到的文本.图片.音频. ...

  9. Java序列化与反序列化

    Java序列化与反序列化是什么?为什么需要序列化与反序列化?如何实现Java序列化与反序列化?本文围绕这些问题进行了探讨. 1.Java序列化与反序列化 Java序列化是指把Java对象转换为字节序列 ...

随机推荐

  1. android的ADK下载地址

    把下面所有的包下载到temp目录下进行安装. 用代理http://ppdaili.com/https://dl-ssl.google.com/android/repository/repository ...

  2. String源码图

    String StringBuffer StringBuilder 均为对字符数组的操作. 实现了不同的接口,导致不同的覆写. 实现了同样的接口,适应不同的场景.

  3. vue2 vue-router 组装

    适用于vue cli搭建的项目 vue-router模块下载及记录到package.json中: npm i vue-router -D main.js中: import VueRouter from ...

  4. WebRTC 入门到放弃(一)WebRTC

    前言 WebRTC,名称源自网页实时通信(Web Real-Time Communication)的缩写,是一个支持网页浏览器进行实时语音对话或视频对话的技术,是谷歌2010年以6820万美元收购Gl ...

  5. Python函数返回不定数量的值

    Python的函数是可以return多个值的,但其本质上还是返回单个值,只是利用了tuple的自动打包,将多个值打包成单个tuple返回. 使用代码验证: def func_a(): return 1 ...

  6. App开发 对生命周期的处理

    //获取到当前所在的视图 - (UIViewController *)presentingVC:(UIApplication *)application{ UIWindow * window = ap ...

  7. Babel 转码器 § es6转换es5

    Babel 转码器 § es6转换es5 实时转码 /  Repl  -babel-node / babel-register(自动转码引入babel-register模块) 配置文件.babelrc ...

  8. CAD 二次开发 -- 自动加载开发的DLL

    CAD二次开发可以采用写扩展DLL的方式实现.该DLL的函数可以被CAD调用. 但是调用前,必须用命令netload 将该dll加载到CAD. 其实可以修改注册表,当CAD软件启动后,自动加载扩展DL ...

  9. Sampling

    本文主要涉及接受拒绝采样,重要性采样,蒙特卡洛方法,吉布斯采样等内容.部分内容整理与互联网.仅供交流学习使用!

  10. java_web学习(八) jdbc连接mysql

    首先我们来看一下主机与数据库的关系图 实际上是两台服务器 一:下载数据库驱动jar包存放WebContent—WEB-INF—lib目录下 1.2步骤 1. 2. 3 4. 1.3 将jar包导入到W ...