coreJava: serialVersionUID

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/

你可能感兴趣的:(coreJava: serialVersionUID)