I had an object
public class Foo implements Serializable {
private List<Bar> barList;
// getters and setters
}
(Bar also implements Serializable.)
FindBugs threw a violation SE_BAD_FIELD. Which is fair enough, because List is not transient or Serializable. However, I want to serialize this list! So I'm going to need to write writeObject and readObject myself.
I had a look at the ArrayList implementation of writeObject in the JDK, which is fairly straightforward but also a little more complicated than I thought. Here it is:
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
// Write out element count, and any hidden stuff
int expectedModCount = modCount;
s.defaultWriteObject();
// Write out size as capacity for behavioural compatibility with clone()
s.writeInt(size);
// Write out all elements in the proper order.
for (int i=0; i<size; i++) {
s.writeObject(elementData[i]);
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
I had expected it would just do the part called "Write out all elements in the proper order" above. But it seems to be a bit more complex than that. Do I need to copy the stuff into my implementation of writeObject inside Foo?
- Do I need to call default write if I am going to be generating a new ArrayList to write the objects into? The private fields of the list itself probably don't need to be retained.
- What is the point of writing the size separately, when the size will be written in the default write? The size is ignored in the corresponding
readObjectimplementation. - Is there any way for me to replicate the
modCountbehaviour given that I don't have access to the protectedmodCountfield? Should I putwriteObjectinside asynchronizedblock?
Thanks!
private ArrayList<Bar> barList