...
Code Block | ||
---|---|---|
| ||
class MutableSer implements Serializable { private Date date = null; // mutableMutable component public MutableSer(Date d){ date = new Date(d.getTime()); // constructorConstructor performs defensive copying } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); //perform Perform validation if necessary } } |
...
Code Block | ||
---|---|---|
| ||
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); //defensively Defensively copy the mutable component date = new Date(date.getTime()); //perform Perform validation if necessary } |
Wiki Markup |
---|
There is no need to copy immutable sub-objects. Also, avoid using the sub-object's {{clone()}} method because it can be overridden when the sub-object's class is non-final. The sub-objects ({{date}}) themselves must be non-final so that defensive copying can occur. It is also inadvisable to use the {{writeUnshared()}} and {{readUnshared()}} methods as an alternative \[[Bloch 08|AA. Java References#Bloch 08]\]. |
...