Here's a simplified class:
class Foo implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Set<Foo> children;
public Foo( Integer id ) {
if( id == null ) {
throw new IllegalArgumentException( );
}
this.id = id;
this.children = new HashSet<Foo>( 16 );
}
@Override public int hashCode( ) {
return id.hashCode( );
}
...
}
As you can see, it contains a set of itself, and uses its id
property to generate a hash. But I have an issue when the object has a self-referential loop:
When the object is de-serialised, processing follows the children to the deepest object first, then builds backwards. That's usually fine, but if an object contains one of the higher objects in its children
set it breaks: When it tries to add this object to its HashSet, it calls hashCode
, but id
hasn't been loaded for that object yet, so it crashes with a NullPointerException.
(It took me quite a while to track that down!)
So my question is: can I control the order of serialisation? I need to have id
serialised (and de-serialised) before children
.