今天在偶然的机会看到了有关序列化的问题,我们都知道在接口调用的时候,如果是两台服务器之间的数据传输,传输的实体类如果没有进行序列化的话是会报错的,但是有的时候是不需要进行序列化的,这个时候就需要用到一个关键字transient。
首先用一个小例子来表示一下,首先是实体类,在里面的面积属性加上关键字:
package com.zsh.demo;
import java.io.Serializable;
public class Rectangle implements Serializable {
/**
* 序列化ID,一般都会加上
*/
private static final long serialVersionUID = 1L;
/**
* 长
*/
private Integer width;
/**
* 高
*/
private Integer height;
/**
* 面积
*/
private transient Integer area;
public Rectangle(Integer width, Integer height) {
super();
this.width = width;
this.height = height;
this.area = width * height ;
}
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
public Integer getArea() {
return area;
}
public void setArea() {
this.area = this.width * this.height;
}
@Override
public String toString() {
return "Rectangle [width=" + width + ", height=" + height + ", area=" + area + "]";
}
}
然后就是测试方法了 ,首先将其输出,看看本来的数据,然后利用IO将数据转换一次,再次输出:
package com.zsh.demo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TransientExample {
public static void main(String[] args) throws Exception {
//首先计算一个面积
Rectangle rc = new Rectangle(2, 3);
System.out.println("原始的实体:"+rc.toString());
File f = new File("");
String absolutePath = f.getAbsolutePath();
System.out.println(absolutePath);
System.out.println(Rectangle.class.getSimpleName());
System.out.println(absolutePath +"\\"+ Rectangle.class.getSimpleName());
//利用IO操作
//ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("E:/workspace1/workspace-for-test/transient/Rectangle"));
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(absolutePath +"/"+ Rectangle.class.getSimpleName()));
out.writeObject(rc);
out.close();
// 从流读取对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream("rectangle"));
Rectangle rectangle1 = (Rectangle)in.readObject();
System.out.println("2.反序列化后的对象\n"+rectangle1);
rectangle1.setArea();
System.out.println("3.恢复成原始对象\n"+rectangle1);
in.close();
}
}
从结果上面看,我们可以看到,IO转换后实体类的面积属性会编程null,所以,这个关键字的作用就是将指定的属性不进行序列化,比如这些可以计算的属性等,以此减少内存开销。