import java.io.Serializable;
/**
* @Description transient关键字 被修饰的字段不会被序列化传输(继承Serializable)
* @Author rll
* @Date 2021-01-04 10:16
*/
public class User implements Serializable {
private static final long serialVersionUID = 5001293179270499108L;
private String name;
private transient String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
import java.io.*;
/**
* @Description transient关键字
* @Author rll
* @Date 2021-01-04 10:21
*/
public class TransientTest {
public static void main(String[] args) {
User u1= new User();
u1.setName("testName");
u1.setPwd("pwd123");
System.out.println("read before Serializable: ");
System.out.println("username: " + u1.getName());
System.err.println("password: " + u1.getPwd());
String fileName = "D:/user.txt";
//写入文件
try {
ObjectOutputStream oops = new ObjectOutputStream(new FileOutputStream(fileName));
oops.writeObject(u1);
oops.flush();
oops.close();
} catch (IOException e) {
e.printStackTrace();
}
//读取对象
try {
ObjectInputStream oips = new ObjectInputStream(new FileInputStream(fileName));
User u2 = (User) oips.readObject();
oips.close();
System.out.println("read after Serializable: ");
System.out.println("username: " + u2.getName());
System.err.println("password: " + u2.getPwd());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}