实现Serializable
@Test
public void serializableTest(){
try {
User u=new User(11,"喵喵喵");
ObjectOutputStream op=new ObjectOutputStream(new FileOutputStream("/Users/macmini/Desktop/aa"));
op.writeObject(u);
op.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void serializableTest2(){
try {
ObjectInputStream oi=new ObjectInputStream(new FileInputStream("/Users/macmini/Desktop/aa"));
User u= (User) oi.readObject();
System.out.println(u);
System.out.println(u.getAge()+":"+u.getName());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static final long serialVersionUID=1L;
在类中声明 static final 修饰的常量 serialVersionUID后,当类中的成员有所改变时,还是可以最大程度的反序列化,否则程序会报错。