#####一、transient关键字
transient:字面意思临时短暂;
在java中修饰变量表示只存在于内存中,当序列化至磁盘时不保存,如TreeMap中就有此关键字使用;
测试代码
package com.sjjg.rbtree;
import java.io.Serializable;
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer id;
private transient String name;//此变量在在序列化时不会保存值
private Integer sex;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(Integer id, String name, Integer sex) {
super();
this.id = id;
this.name = name;
this.sex = sex;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", sex=" + sex + "]";
}
}
测试效果
package com.sjjg.rbtree;
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 MainTest {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
// xlh();
fxlh();
}
public static void fxlh() throws IOException, IOException,
ClassNotFoundException{
//序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
"d:/data.txt"));
Person p = new Person(25, "zhangsan", 1);
oos.writeObject(p);
oos.close();
//反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"d:/data.txt"));
Person p1 = (Person) ois.readObject();
System.out.println(p1);
//Person [id=25, name=null, sex=1]
ois.close();
/**未使用 transient修饰name变量时
* sr com.sjjg.rbtree.Person L idt Ljava/lang/Integer;L namet Ljava/lang/String;L sexq ~ xpsr java.lang.Integer鉅亣8 I valuexr java.lang.Number啲?斷? xp t zhangsansq ~
使用 transient修饰name变量时
* sr com.sjjg.rbtree.Person L idt Ljava/lang/Integer;L sexq ~ xpsr java.lang.Integer鉅亣8 I valuexr java.lang.Number啲?斷? xp sq ~
*/
}
}
对象序列化讲解:
https://www.cnblogs.com/dongguacai/p/5721056.html