在Java中, transient字段在序列化过程中被排除。 简而言之,当我们将对象保存到文件中(序列化)时,所有transient字段都将被忽略。
1. POJO +瞬态
复查以下Person类; 薪水领域是transient 。
public class Person implements Serializable {private static final long serialVersionUID = 1L;private String name;private int age;// ignore this fieldprivate transient BigDecimal salary;//...
}
2.序列化
2.1在序列化期间,瞬态现场salary将不包括在内。
ObjectUtils.java
package com.mkyong.io.object;import java.io.*;
import java.math.BigDecimal;public class ObjectUtils {public static void main(String[] args) throws IOException, ClassNotFoundException {Person person = new Person("mkyong", 40, new BigDecimal(900));// object -> filetry (FileOutputStream fos = new FileOutputStream("person.obj");ObjectOutputStream oos = new ObjectOutputStream(fos)) {oos.writeObject(person);oos.flush();}Person result = null;// file -> objecttry (FileInputStream fis = new FileInputStream("person.obj");ObjectInputStream ois = new ObjectInputStream(fis)) {result = (Person) ois.readObject();}System.out.println(result);}}
2.2现在,我们删除了transient关键字。
Person.java
public class Person implements Serializable {private static final long serialVersionUID = 1L;private String name;private int age;private BigDecimal salary;//...
}
重新运行它,这次将显示薪水字段。
Terminal
Person{name='mkyong', age=40, salary=900}