Question 6
Given:
10. public class Foo implements java.io.Serializable {
11. private int x;
12. public int getX() { return x; }
12.publicFoo(int x){this.x=x; }
13. private void writeObject( ObjectOutputStream s)
14. throws IOException {
15. // insert code here
16. }
17. }
Which code fragment, inserted at line 15, will allow Foo objects to be
correctly serialized and deserialized?
A. s.writeInt(x);
B. s.serialize(x);
C. s.writeObject(x);
D. s.defaultWriteObject();
Answer: DQuestion 7
Click the Exhibit button.
1. import java.io.*;
2. public class Foo implements Serializable {
3. public int x, y;
4. public Foo( int x, int y) { this.x = x; this.y = y; }
5.
6. private void writeObject( ObjectOutputStream s)
7. throws IOException {
8. s.writeInt(x); s.writeInt(y)
9. }
10.
11. private void readObject( ObjectInputStream s)
12. throws IOException, ClassNotFoundException {
13.
14. // insert code here
15.
16. }
17. }
Which code, inserted at line 14, will allow this class to correctly
serialize and deserialize?
A. s.defaultReadObject();
B. this = s.defaultReadObject();
C. y = s.readInt(); x = s.readInt();
D. x = s.readInt(); y = s.readInt();
Answer: D为什么下面这个可以用writeInt() 而上面那个只能用defaultWirteObject()

解决方案 »

  1.   

    因为第一个没有对应的readObject方法来对Foo进行相应的反序列化,仔细读一下问题:
    Which code fragment, inserted at line 15, will allow Foo objects to be
    correctly serialized and deserialized
    不是单说能不能在这里加上代码而编译没有错,而是还要考虑到能否"正确"实现序列化/反序列化的功能.而第二个有对应readObject的方法来把x,y分别set回去.
      

  2.   

    题目跟你玩了一个小把戏而已。
    Question 6
      因为没有写private void readObject( ObjectInputStream s)方法,所以你要保证能够被正确反序列化的话需要用defaultWriteObject().
      如果说程序有写private void readObject( ObjectInputStream s) throw ...{x = s.readInt()}的话用“s.writeInt(x)”也是可以的,这只是考你的细心程度而也Question 7
      因为writeObject和readObject都有,,所以。。
      

  3.   

    楼上说的问题我也注意到了,主要是我想知道为什么defaultWriteObject()就可以,是readObject()方法也会调用defaultReadObject()吗 序列化和反序列化不是要保持一致的吗
      

  4.   

    记忆中这个好象是规范
    这个是给你自定义要怎么去序列化的
    然后defaultReadObject()
    是writeObject()的默认实现
      

  5.   


    defaultWriteObject()就是把默认的非static 非transient的变量都序列化。任何一个序列化类都有一个ObjectStreamClass与之对应,default就是根据ObjectStreamClass和反射找到那些变量需要序列化,然后就序列化了。。