transient关键字的定义
定义:transient只能用来修饰成员变量(field),被transient修饰的成员变量不参与序列化过程。
简析:Java中的对象如果想要在网络上传输或者存储在磁盘时,就必须要序列化。Java中序列化的本质是Java对象转换为字节序列。但是在序列化的过程中,可以允许被序列对象中的某个成员变量不参与序列化,即该对象完成序列化之后,被transient修饰的成员变量会在字节序列中消失。
小明的昵称希望被人看到,但是真名不希望被人看到。
package com.ygl.demo3;
import java.io.Serializable;
public class XiaoMing implements Serializable {
private static final long serialVersionUID = 1271321732347324L;
private String nickName;
private transient String realName;
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public XiaoMing(String nickName, String realName) {
this.nickName = nickName;
this.realName = realName;
}
@Override
public String toString() {
return "XiaoMing{" +
"nickName='" + nickName + '\'' +
", realName='" + realName + '\'' +
'}';
}
}
package com.ygl.demo3;
import java.io.*;
public class TestXiaoMing {
public static void main(String[] args) throws IOException {
XiaoMing xiaoMing = new XiaoMing("ming", "鸿铭");
System.out.println("序列化前:"+xiaoMing.toString());
ObjectOutputStream oo = null;
ObjectInputStream oi = null;
try {
oo = new ObjectOutputStream(new FileOutputStream(new File("./xiaoming.txt")));
oo.writeObject(xiaoMing);
oi = new ObjectInputStream(new FileInputStream(new File("./xiaoming.txt")));
XiaoMing x = (XiaoMing) oi.readObject();
System.out.println("序列化后:"+x.toString());
}catch (IOException | ClassNotFoundException e){
System.out.println(e.getStackTrace());
}finally {
oi.close();
oo.close();
}
}
}
结果
序列化前:XiaoMing