主题:[原创]SCJP考试试题解析二
SCJP考试试题解析二
我的QQ号:2535279
我的QQ群:58591592
www.javaedu.com.cn
import java.io.*;
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 s) throws IOException {
s.writeInt(x);
s.writeInt(y);
}
private void readObject(ObjectInputStream s) throws IOException,
ClassNotFoundException {
//insert code here-->line 14
}
}
Which code,insertd at line 14,will allow this class to correctly serialized and deserialized?
A. s.defaultReadObject();
B. this=s.defaultReadObject();
C. y=s.default();x=s.readInt();
D. x=s.readInt();y=s.readInt();
可能大家看到这个程序有点奇怪,为什么要实现
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream) throws IOException
这两个方法呢.因为,在OutputStream里面有个规定,"在序列化和反序列化过程中需要特殊处理的类必须实现具有实现具有下列准确签名的特
殊方法:
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException;
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException
private void readObjectNoData()
throws ObjectStreamException;
我们这个程序里面除了基本数据类型int外,并没有其他的特殊的类啊.呵呵,这里只是一个例子,抛砖引玉吧.
我们在wirteObject这个方法中,用writeInt方法,实现了将x,y写入ObjectOutputStream的目的,那么,很容易想到,我们要是想从
ObjectInputStream中读出这两个数据,我们应该用readInt方法来实现.
所以,答案为:D
为了看到效果,我自己写了一个测试类
import java.io.*;
public class Tester {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
Foo f = new Foo(4, 5);
FileOutputStream fos = new FileOutputStream("foo.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(f);
FileInputStream fis = new FileInputStream("foo.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Foo f1 = (Foo) ois.readObject();
System.out.println(f1.x + "\t" + f1.y);
}
}
结果显示为:4 5