1、序列化就是将对象写入io流的过程。
2、反序列化就是从io流中提取对象的过程。
这是在网络传输的过程中需要必须进行的操作,也是为了网络传输的安全性。所以建议每个JavaBean都需要进行序列化操作。
通常我们序列化是让某个对象实现Serializable接口,就会自动序列化。
有些场景我们传输对象的时候不能对所有的字段进行序列化。比如一些敏感的字段:身份证、密码等等。
那么我们就只需要在不要序列化的变量前面加上transient关键字进行修饰就可以了
看代码
import java.io.*;
public class TransientTest implements Serializable {
public TransientTest(){
}
private transient String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static void main(String[] args) {
try{
//序列化过程
TransientTest transientTest = new TransientTest();
transientTest.setContent("是否有被序列化");
transientTest.setName("苏");
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(("d://1.txt"))));
oos.writeObject(transientTest);
oos.close();
//反序列化过程
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("d://1.txt"));
TransientTest test = (TransientTest)ois.readObject();
System.out.println("content="+test.getContent());
System.out.println("name="+test.getName());
}catch(Exception e){
e.printStackTrace();
}
}
}
##结果
content=null
name=苏
序列化后保存在txt中的样子是这样的
上面代码对content字段用transient关键字进行了修饰,序列化TransientTest对象时,就不对content字段进行序列化,所以反序列化得到的结果自然是为null。