当检查java.util.ArrayList实现时,注意到arrayList中的元素数据对象数组是瞬态的,即使ArrayList是可序列化的。
transient Object[] elementData; // non-private to simplify nested class access
那么arrayList如何通过保持elementData数组瞬态来保护其在反序列化过程中的数据?
标记成员transient
并不意味着该字段没有被序列化,只是它没有使用Java的字段内置序列化机制自动序列化。
在ArrayList
序列化的情况下,通过自定义writeObject
方法执行:[src]
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();
}
}
使用readObject
进行反序列化。