coreJava: serialVersionUID

2448 ワード

EclipseはserialVersionUIDをチェックしますが、private static final long serialVersionUID=1 Lを定義します.いいです.
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を2 Lに変更すると、serialVersionUIDが異なるため、エラーが発生します.
 
From: http://www.mkyong.com/java-best-practices/understand-the-serialversionuid/