transient有「臨時的」,"短暫的"含義,咱們瞭解過Serializable,Java序列化,當對某些變量咱們不想對它進行序列化的時候就能夠將此變量設置爲transient,transient是Java語言的關鍵字,用來表示一個域不是該對象串行化的一部分。transient說明一個屬性是臨時的,不會被序列化。java
public class TransientDemo implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private transient String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { // TODO Auto-generated method stub String path="D:"+File.separator+"object.txt"; File file=new File(path); TransientDemo transientDemo=new TransientDemo(); transientDemo.setName("姓名"); transientDemo.setPassword("密碼"); ObjectOutput output=new ObjectOutputStream(new FileOutputStream(file)); output.writeObject(transientDemo); ObjectInput input=new ObjectInputStream(new FileInputStream(file)); TransientDemo demo=( TransientDemo )input.readObject(); System.out.println(demo.getName()+demo.getPassword()); } }
結果name輸出爲nullthis