TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
java中Vo类实现了Serializable标示可序列化的,此时有:
private static final long serialVersionUID = 1L;[/code]
这个值是为了序列化和反序列化的时候使用的,如果类发生了改变如:增加方法或者增加了属性那么需要从新生成这个值,这个值的生成是基于此类的属性、方法、类名、表明而生成的一个唯一long型的hash值。
序列化和反序列化采用ObjectOutputStream和ObjectInputStream
如果版本相同,序列化之后增加了一个属性那么在serialVersionUID不变的情况下反序列化回来对应的属性为null,如果升级了版本那么报错。
其他代码如下:
class Student implements Serializable {
private static final long serialVersionUID = -8128337695736294309L;
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + id + "]";
}
}[/code] ? public static void writeObject(Object o) throws Exception {
File f = new File("d:/user.tmp");
if (f.exists()) {
f.delete();
}
FileOutputStream os = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(o);
oos.close();
os.close();
}[/code]
public static Student readObject(File f) throws Exception {
InputStream is = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(is);
return (Student) ois.readObject();
}
[/code] |
|