使用对象流保存对象时,将对象的全部信息都保存了,但是有些信息是不希望保存,如密码,该如何避免该信息的保存。
使用transient关键字修饰的属性,在保存对象时,该属性并不会被保存。
下面的程序定义了一个Usere类,它包含用户名,密码、年龄,其中密码和年龄被transient关键字修饰,此外,该类还实现了 Serializable 接口。
public class User implements Serializable {
private static final long serialVersionUID = 3601470141407549788L;
private String userName;
private transient String password;
private transient int age;
public User(String userName, String password, int age) {
this.userName = userName;
this.password = password;
this.age = age;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
编写一个test类
@Test
public void test25(){
ObjectOutputStream oos = null;
User user = new User("章子怡","123456",25);
try {
oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream("ObjectData")));
oos.writeObject(user);
System.out.println("保存对象前: ");
System.out.println("用户姓名: "+user.getUserName());
System.out.println("用户密码: "+user.getPassword());
System.out.println("用户年龄: "+user.getAge());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream("ObjectData")));
try {
User user1 = (User)ois.readObject();
System.out.println("保存对象后: ");
System.out.println("用户姓名: "+user1.getUserName());
System.out.println("用户密码: "+user1.getPassword());
System.out.println("用户年龄: "+user1.getAge());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
总结:
transient用于修饰不需要序列化的字段,如果一个引用类型被transient修饰,则其反序列化的值为null,如果一个基本类型被transient修饰,则其反序列化的值为0
,如果字段的引用类型是不可序列化的类,则也应该使用transient修饰,它在序列化时会被直接跳过。