- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
当我读到Thinking in java
中关于Serializable
接口(interface)的时候,有一句话是这样说的:
If you use the default mechanism to write the non-transient parts of your object, you must call defaultWriteObject( ) as the first operation in writeObject( ), and defaultReadObject( ) as the first operation in readObject( ).
并且在 docs.oracle.com 5.6.2 :
Adding writeObject/readObject methods - If the version reading the stream has these methods then readObject is expected, as usual, to read the required data written to the stream by the default serialization. It should call defaultReadObject first before reading any optional data. The writeObject method is expected as usual to call defaultWriteObject to write the required data and then may write optional data.
所以如果我不先调用defaultWriteObject
,如果我在那个调用之前写了别的东西,会有什么问题吗?我已经尝试过了,但在我的示例中它似乎仍然运行良好。那么如果有任何问题,它会在什么条件下发生?
最佳答案
Java 对象序列化规范在这个主题上含糊不清:
Either
ObjectOutputStream
'sdefaultWriteObject
orwriteFields
method must be called once (and only once) before writing any optional data that will be needed by the correspondingreadObject
method to restore the state of the object; even if no optional data is written,defaultWriteObject
orwriteFields
must still be invoked once. IfdefaultWriteObject
orwriteFields
is not invoked once prior to the writing of optional data (if any), then the behavior of instance deserialization is undefined in cases where theObjectInputStream
cannot resolve the class which defined thewriteObject
method in question.
这是一个 old thread这给出了可能出现问题的示例。
这是一个 JBoss AS Jira ticket再举一个例子。
关于java - 为什么在写入 ObjectOutputStream 时必须首先调用 defaultWriteObject 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16239239/
为什么需要将 defaultReadObject() 和 defaultWriteObject() 作为 readObject(ObjectInputStream o) 和 中的第一条语句writeO
我正在序列化的类中有一个 writeObject 方法,并且我在其中调用 defaultWriteObject。这里有什么问题吗?字段密码是我尝试加密然后自行解密的 transient 字段。当我运行
当我读到Thinking in java中关于Serializable接口(interface)的时候,有一句话是这样说的: If you use the default mechanism to w
我是一名优秀的程序员,十分优秀!