題目:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Foo implements Serializable{
public int x,y;
public Foo(int x,int y){this.x = x;this.y=y;}
private void writeObject(ObjectOutputStream os) throws IOException{
os.writeInt(x);os.writeInt(y);
}
private void readObject(ObjectInputStream os) throws IOException, ClassNotFoundException{
//insert code here
}
}
----------------------------
private void writeObject(ObjectOutputStream os){
os.writeInt(x);os.writeInt(y);
}
這裡需要丟出例外,因此要加入try/catch或throw Excetion
----------------------------
完整可執行的程式碼:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Foo implements Serializable{
public static void main(String[] args) {
Foo f = new Foo(0, 0);
}
public int x,y;
public Foo(int x,int y){this.x = x;this.y=y;}
private void writeObject(ObjectOutputStream os) throws IOException{
os.writeInt(x);os.writeInt(y);
}
private void readObject(ObjectInputStream os) throws IOException, ClassNotFoundException{
x=os.readInt();y=os.readInt();
}
}
--------------------------------
os.defau;tReadObject(); 可執行但不符合題意
this = os.defaultReadObject(); 錯誤,不能這樣給this
y=os.default();x=os.readInt(); 錯誤,根本沒有default()這個方法
x=os.readInt();y=os.readInt(); 正解
本題要序列化與復用FOO,既然用writeObject(os)方法來接收ObjectInputStream物件os,相對應要撰寫一個readObject(os)將物件os的內容值讀出。