1、transient关键字只能修饰变量,而不能修饰方法和类。
2、被transient关键字修饰的变量不再能被序列化,一个静态变量不管是否被transient修饰,均不能被序列化。
3、一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法获得访问。也可以认为在将持久化的对象反序列化后,被transient修饰的变量将按照普通类成员变量一样被初始化。
package com.design.prompt;
import java.io.Serializable;
public class UserTest implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6522988290199824802L;
private String username;
transient String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.design.prompt;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.junit.Test;
public class TransientTest {
@Test
public void test_transient() {
UserTest ut = new UserTest();
ut.setUsername("jane");
ut.setPassword("123456");
System.out.println("read before Serializable: ");
System.out.println("before username: " + ut.getUsername());
System.err.println("before password: " + ut.getPassword());
try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("C:/user.txt"));
os.writeObject(ut); // 将User对象写进文件
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(
"C:/user.txt"));
ut = (UserTest) is.readObject(); // 从流中读取User的数据
is.close();
System.out.println("\nread after Serializable: ");
System.out.println("after username: " + ut.getUsername());
System.err.println("after password: " + ut.getPassword());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
执行结果:
before password: 123456
read before Serializable:
before username: jane
after password: null
read after Serializable:
after username: jane