在需要将对象序列化,但是不想序列化敏感信息时,使用transient关键字对jvm“说”我不想要序列化这个属性,注意transient只能运用在属性上,不能在方法,类。
如:
public class User implements Serializable {
private static final long serialVersionUID = -8069315638464847330L;
private String userName;
private 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;
}
}
使用:
public class Main {
public static void main(String[] args) throws IOException {
User user = new User();
user.setUserName("liao");
user.setPassword("liso");
System.out.println("read before Serializable: ");
System.out.println("username: " + user.getUserName());
System.out.println("password: " + user.getPassword());
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("user.txt"));
outputStream.writeObject(user);
outputStream.flush();
outputStream.close();
}
}
ps:如果要序列化某个对象,需要在该对象的类实现Serializable接口,且生成serialVersionUID,在反序列化的时候与本地的类的serialVersionUID进行比较,一致则可以进行反序列化,不一致则会抛出异常InvalidCastException。