java对象序列化和反序列化、transient关键字
实现对象的序列化,必须对象实现Serializable接口
1.Java对象序列化的应用场景
- 将对象保存至文件
- 将对象保存至数据库
- 服务之间传输对象
2.所用类 ObjectOutputStream 、ObjectInputStream
File file = new File("D:/test.txt");
Student student = new Student("孙悟空", "12");
try {
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
outputStream.writeObject(student);
outputStream.close();
System.out.println("序列化成功");
} catch (IOException e) {
e.printStackTrace();
}
}
File file = new File("D:/test.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
Student s = (Student) objectInputStream.readObject();
System.out.println(s.toString());
System.out.println("对象反序列化成功");
3.transient关键字
transient只能修饰对象的属性,不能修饰类或者方法
被transient修饰的属性,不会被序列化。
private static final long serialVersionUID = 1L;
private String name;
private transient String age;
执行了上面的ObjectOutputStream ,ObjectInputStream操作
得到的结果:
可以看到当age属性被transient修饰后,不会被序列化保存到文件中
注:被static修饰的属性,也不会被序列化,此属性迟被放入了静态池