天天看点

transient关键字

transient

transient是短暂的意思。

对于transient 修饰的成员变量,在类的实例对象的序列化处理过程中会被忽略。 因此,transient变量不会贯穿对象的序列化和反序列化,生命周期仅存于调用者的内存中而不会写到磁盘里进行持久化。

序列化

序列化使用<code>objectoutputstream.writeobject(e)</code>方法。

transient关键字

反序列化使用<code>objectinputstram.readobject()</code>方法

transient关键字

<code>static</code>修饰的变量同样不会序列化!

arraylist中的<code>transient</code>:

transient关键字

为什么arraylist还能序列化呢?

很简单,重写riteobject()和readobject()方法就好了

又有一个问题,既然想序列化,arraylist为什么又要使用transient呢?

因为容量的问题,elementdata里面有一些元素是空的,这种是没有必要序列化的。所以使用transient屏蔽数组,使用默认方法将其他属性序列化之后,在单独处理elementdata[] 我们来看看arrallist源码重写的的writeobject(),可以看到,它先把除了transient element[]之外的属性序列化,然后单独处理element[size](非空元素)。
transient关键字