Eclipse会检查serialVersionUID,其实定义private static final long serialVersionUID = 1L; 就可以。
serialVersionUID只是序列化转换时的一个判别符(判别类是否改变)。
附件为代码。
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
String street;
String country;
public void setStreet(String street) {
this.street = street;
}
public void setCountry(String country) {
this.country = country;
}
public String getStreet() {
return this.street;
}
public String getCountry() {
return this.country;
}
@Override
public String toString() {
return new StringBuffer(" Street : ").append(this.street).append(" Country : ").append(this.country).toString();
}
}
public class WriteObject {
public static String fileName = "f:\\address.ser";
public static void main(String args[]) {
Address address = new Address();
address.setStreet("Xi Dan");
address.setCountry("China");
try {
FileOutputStream fout = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(address);
oos.close();
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public class ReadObject {
public static void main(String args[]) {
Address address;
try {
File file = new File(WriteObject.fileName);
if (!file.exists())
WriteObject.main(null);
FileInputStream fin = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fin);
address = (Address) ois.readObject();
ois.close();
System.out.println(address);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
输出结果为:Street : Xi Dan Country : China
但如果修改serialVersionUID为2L, 那么就会报错,因为serialVersionUID不同。
From:http://www.mkyong.com/java-best-practices/understand-the-serialversionuid/
本文详细解释了序列化版本ID(serialVersionUID)的作用及其重要性,包括其在序列化过程中的唯一标识作用,防止因类结构变化导致的序列化不兼容问题,并通过代码实例展示了如何正确设置该属性。
7224

被折叠的 条评论
为什么被折叠?



