在系统运行的时候,如果你需要将某个对象的信息保存下来。以便在后来的某个时刻调用,除了缓存,还可以使用序列化。
1 首先,要序列化的实体类必须实现 Serializable (这是一个标记接口,不用重写任何方法)。需要说明的是实体类的方法不会被序列化,transient关键字修饰的属性也不会被序列化,如果你不希望某个字段被序列化,可以用transient关键字修饰它。
public class User implements Serializable{
private static final long serialversionUID = 223343435454543543L;
private String name;
private int age;
private transient String phone;
public void say(){
System.out.println("方法不会被序列化,transient 关键字修饰的属性也不会被序列化");
}
//setter、getter方法就不写了
}
2 新建一个测试类
public class SerializeTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
xlh();//序列化
fxlh();//反序列化
}
public static void xlh() throws IOException{
User user = new User();
user.setAge(22);
user.setName("赵**");
user.setPhone("1234567890");
String path = "E:\\JAVA_TEMP\\serialize.txt";//序列化文件保存的路径
File file = new File(path);
OutputStream oos = new FileOutputStream(file);
ObjectOutputStream os = new ObjectOutputStream(oos);
os.writeObject(user);
}
public static void fxlh() throws IOException, ClassNotFoundException{
String path = "E:\\JAVA_TEMP\\serialize.txt";
File file = new File(path);
InputStream iis = new FileInputStream(file);
ObjectInputStream is = new ObjectInputStream(iis);
User user = (User) is.readObject();
user.say();
System.out.println(user.getAge());
System.out.println(user.getName());
}
}
可以看到,序列化用到的两个Object流 ObejectOutPutStream 、ObjectInputStream 来实现序列化和反序列化的.
运行结果:
方法不会被序列化,transient 关键字修饰的属性也不会被序列化
22
赵**
注意,phone属性被transient关键字修饰了,反序列化得到得对象的phone为null