1.transient关键字的作用和使用方法
- transient关键字的作用:一个类实现了Serializable接口,这个类定义的对象就可以序列化和反序列化。不需要序列化的属性加上transient关键字修饰。
- transient关键字只能修饰变量,不能修饰方法和类。
- transient关键字使用示例:
// 密码信息作为敏感信息,为了安全起见,不需要序列化
// 实现Serializable接口,支持序列化和反序列化
public class User implements Serializable {
private String userName;
private transient String password;
// get,set
}
public class TransientTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
User user = new User();
user.setUserName("root");
user.setPassword("123456");
//序列化前:root,123456
System.out.println("序列化前:" + user.getUserName() + "," + user.getPassword());
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("object.txt"));
// 将对象序列化文件里
outputStream.writeObject(user);
outputStream.flush();
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("object.txt"));
// 从流中读取数据
User object = (User) inputStream.readObject();
// 序列化后root,null
System.out.println("序列化后" + object.getUserName() + "," + object.getPassword());
inputStream.close();
outputStream.close();
}
}
- 如何序列化被transient关键字修饰的类变量:实现Externalizable接口.
- 被static修饰的类变量不管是否使用transient关键字修饰,都是不能被序列化的。
//反序列化后类中static型变量的值实际上是当前JVM中对应static
//变量的值,这个值是JVM中的并不是反序列化得出的
public class User implements Serializable {
private String userName;
private static String password;
// set,get
}
public class TransientTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
User user = new User();
user.setUserName("root");
user.setPassword("123456");
//序列化前:root,123456
System.out.println("序列化前:" + user.getUserName() + "," + user.getPassword());
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("object.txt"));
// 将对象序列化文件里
outputStream.writeObject(user);
outputStream.flush();
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("object.txt"));
// 测试静态的password属性是否被序列化
user.setPassword("root");
// 从流中读取数据
User object = (User) inputStream.readObject();
// 序列化后root,root
System.out.println("序列化后" + object.getUserName() + "," + object.getPassword());
inputStream.close();
outputStream.close();
}
}
- final关键字修饰的变量如果不使用transient关键字修饰,也参与序列化