我定期看到具有以下結構的Java類:
class MyClass implements Serializable {
private static final long serialVersionUID = 1L;
// ...
private void writeObject(final java.io.ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
}
private void readObject(final java.io.ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
}
}
據我所知,對于默認序列化,您只需要聲明可序列化接口的實現并定義serialVersionUID.是否有任何理由使用默認實現聲明寫/讀方法?我厭倦了關于代碼重復的分析器警告.
沒有看到任何關于這個主題的非常明確的指南.一切都有點過時或非常主觀.
解決方法:
ObjectInputStream#defaultReadObject和ObjectOutputStream#defaultWriteObject方法適用于您希望使用默認值編寫字段以及您有其他讀取或寫入信息,或者您想要修改讀取或寫入內容的情況.如果您不想添加或更改任何內容,則僅在實現Serializable時添加顯式調用沒有任何優勢.
The default mechanism is used automatically when reading or writing objects that implement the Serializable interface and do no further customization. The serializable fields are mapped to the corresponding fields of the class and values are either written to the stream from those fields or are read in and assigned respectively. If the class provides writeObject and readObject methods, the default mechanism can be invoked by calling defaultWriteObject and defaultReadObject. When the writeObject and readObject methods are implemented, the class has an opportunity to modify the serializable field values before they are written or after they are read.
標簽:java,serialization
來源: https://codeday.me/bug/20190623/1274141.html