一、java的序列化和反序列化
Java对象的序列化就是将对象以二进制方式存储,反序列化是将二进制转换为对象。
1、在Java中,只要一个类实现了java.io.Serializable
接口,那么它就可以被序列化。
2、通过使用ObjectOutputStream
和 ObjectInputStream
对对象进行序列化及反序列化。
3、虚拟机是否允许反序列化,取决于类路径和功能代码是否一致,两个类的序列化 ID(serialVersionUID)是否一致。
4、序列化并不保存静态变量。
5、序列化父类需要父类也实现 Serializable 接口。
6、使用关键字 Transient 标识 该属性不需要被序列化。
二、ArrayList 内部的序列化优化
上源码:
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
private static final long serialVersionUID = 8683452581122892189L;
transient Object[] elementData; // non-private to simplify nested class access
private int size;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
List<String> strings = new ArrayList<String>();
strings.add("测");
strings.add("测2");
strings.add("测3");
strings.add("测4");
System.out.println("strings" + strings);
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("strings")); //序列化写入文件
objectOutputStream.writeObject(strings);
objectOutputStream.close();
File file = new File("strings");
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file)); //反序列化 从文件中读出来
List<String> newStringList = (List<String>)objectInputStream.readObject();
objectInputStream.close();
System.out.println("new strings" + strings);
}
ArrayList底层是通过数组实现的,数组elementData
其实就是用来保存列表中的元素的。
在ArrayList中定义了来个方法: writeObject
和readObject
。
在序列化过程中,如果被序列化的类中定义了writeObject 和 readObject 方法,虚拟机会试图调用对象类里的 writeObject 和 readObject 方法,进行用户自定义的序列化和反序列化。
如果没有这样的方法,则默认调用是 ObjectOutputStream 的 defaultWriteObject 方法以及 ObjectInputStream 的 defaultReadObject 方法。
用户自定义的 writeObject 和 readObject 方法可以允许用户控制序列化的过程,比如可以在序列化的过程中动态改变序列化的数值。
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
elementData = EMPTY_ELEMENTDATA;
// Read in size, and any hidden stuff
s.defaultReadObject();
// Read in capacity
s.readInt(); // ignored
if (size > 0) {
// be like clone(), allocate array based upon size not capacity
ensureCapacityInternal(size);
Object[] a = elementData;
// Read in all elements in the proper order.
for (int i=0; i<size; i++) {
a[i] = s.readObject();
}
}
}
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 size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// 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();
}
}
ArrayList实际上是动态数组,每次在放满以后自动增长设定的长度值,如果数组自动增长长度设为100,而实际只放了一个元素,那就会序列化99个null元素。为了保证在序列化的时候不会将这么多null同时进行序列化,ArrayList把元素数组设置为transient。
为了防止一个包含大量空对象的数组被序列化,为了优化存储,所以,ArrayList使用transient
来声明elementData
。 但是,作为一个集合,在序列化过程中还必须保证其中的元素可以被持久化下来,所以,通过重写writeObject
和 readObject
方法的方式把其中的元素保留下来。
writeObject
方法把elementData
数组中的元素遍历的保存到输出流(ObjectOutputStream)中。
readObject
方法从输入流(ObjectInputStream)中读出对象并保存赋值到elementData
数组中。
三、自定义 writeObject and readObject
在需要序列化的类中重写 writeObject readObject,
这两个方法在使用ObjectOutputStream的writeObject方法和ObjectInputStream的readObject方法时,会通过反射的方式调用。
调用栈:
writeObject ---> writeObject0 --->writeOrdinaryObject--->writeSerialData--->invokeWriteObject
//这段代码是writeObject0中的
//在进行序列化操作时,会判断要被序列化的类是否是Enum、Array和Serializable类型,如果不是则直接
//提示NotSerializableException。
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());
}
}
四、总结
1、如果一个类想被序列化,需要实现Serializable接口。否则将抛出NotSerializableException
异常,这是因为,在序列化操作过程中会对类型进行检查,要求被序列化的类必须属于Enum、Array和Serializable类型其中的任何一种。
2、在变量声明前加上该关键字,可以阻止该变量被序列化到文件中。
3、在类中增加writeObject 和 readObject 方法可以实现自定义序列化策略