我正在阅读Effective Java中的序列化一章。
谁调用 readObject() 和 writeObject()?为什么将这些方法声明为私有?
下面是书中的一段代码
// StringList with a reasonable custom serialized form public final class StringList implements Serializable { private transient int size = 0; private transient Entry head = null; //Other code private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); s.writeInt(size); // Write out all elements in the proper order. for (Entry e = head; e != null; e = e.next) s.writeObject(e.data); } } }
是否有任何特定原因将该变量
size
声明为瞬态,然后在 writeObject 方法中显式写入它?如果它没有被声明为瞬态,它无论如何都会被写入,对吧?