版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
我们知道在Java中只要实现了Serializable接口,这个都可以被序列化,在Android中进行序列化还有一种方式, 就是Parcelable,
而且比Java提供的序列话方式性能更高,但是在实际的开发中我们有些类虽然实现了Serializable接口,但是里面的有些属性不想进行序列化,这个时候就可以在这个变量的前面添加transient修饰了,
class Rectangle implements Serializable {
private static final long serialVersionUID = 1710022455003682613L;
private Integer width;
private Integer height;
private transient Integer area;
public Rectangle (Integer width, Integer height){
this.width = width;
this.height = height;
this.area = width * height;
}
public void setArea(){
this.area = this.width * this.height;
}
@Override
public String toString() {
return "Rectangle{" +
"width=" + width +
", height=" + height +
", area=" + area +
'}';
}
}
public class TransientTest{
public static void main(String args[]) throws Exception {
Rectangle rectangle = new Rectangle(3,4);
System.out.println("1.原始对象"+rectangle);
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("rectangle"));
// 往流写入对象
o.writeObject(rectangle);
o.close();
// 从流读取对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("rectangle"));
Rectangle rectangle1 = (Rectangle)in.readObject();
System.out.println("2.反序列化后的对象"+rectangle1);
rectangle1.setArea();
System.out.println("3.恢复成原始对象"+rectangle1);
in.close();
}
}
上面的求巨型的面积就不需要序列化了,因为根据宽和高就能计算出来,因为序列化就是IO操作,比较耗时的,
注意
transient只能修饰变量 而不能修饰方法 类 局部变量
静态变量是否被transient修饰 都不能被序列化