transient 字段
- 一些不必要同步的字段,在集群间不传递,因此设置为transient
- transient字段就算赋值了,反序列化后,是默认值
一些不必要同步的字段,在集群间不传递,因此设置为transient
因为一些字段没有在要求集群间必须传递,只在各自主机上保持唯一即可.对这样的需求,当然是使用标记transient了.
序列化对象例子
class SpecialSerial implements Serializable {
private static final long serialVersionUID = -4464442243709562174L;
transient int y=100;
static int z = 9;
public SpecialSerial(){
System.out.println("set value for y");
this.y=100;
System.out.println("y:"+y);
};
}
transient字段就算赋值了,就算默认构造函数中有值,反序列化后,还是默认值
public class TestClass {
static public void main(String[] args) {
SpecialSerial s1 = new SpecialSerial();
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myFile"));
os.writeObject(s1);
os.close();
System.out.println("------------------------------------");
ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile"));
SpecialSerial s2 = (SpecialSerial)is.readObject();
is.close();
System.out.println("y:"+s2.y + " ; z:" + s2.z);
} catch (Exception e) {e.printStackTrace();}
}
}
想想也是必然,readObject时候,其实transient的值也是有的,但是这时就已经是默认值了.
输出结果
set value for y
y:100
------------------------------------
y:0 ; z:9
可见,在进行反序列化的时候,并没调用类的构造方法.而是直接根据序列化数据在内存中创建新的对象.
还真没仔细看过关于序列化的文章,看来要详细看下.