protected Object writeReplace ( ) throws ObjectStreamException { WComponent top = WebUtilities . getTop ( this ) ; String repositoryKey ; if ( top instanceof WApplication ) { repositoryKey = ( ( WApplication ) top ) . getUiVersionKey ( ) ; } else { repositoryKey = top . getClass ( ) . getName ( ) ; } if ( UIRegistry . getInstance ( ) . isRegistered ( repositoryKey ) && top == UIRegistry . getInstance ( ) . getUI ( repositoryKey ) ) { // Calculate the node location. // The node location is a list of "shared" child indexes of each // ancestor going right back to the top node. ArrayList < Integer > reversedIndexList = new ArrayList <> ( ) ; WComponent node = this ; Container parent = node . getParent ( ) ; try { while ( parent != null ) { int index = getIndexOfChild ( parent , node ) ; reversedIndexList . add ( index ) ; node = parent ; parent = node . getParent ( ) ; } } catch ( Exception ex ) { LOG . error ( "Unable to determine component index relative to top." , ex ) ; } final int depth = reversedIndexList . size ( ) ; int [ ] nodeLocation = new int [ depth ] ; for ( int i = 0 ; i < depth ; i ++ ) { Integer index = reversedIndexList . get ( depth - i - 1 ) ; nodeLocation [ i ] = index . intValue ( ) ; } WComponentRef ref = new WComponentRef ( repositoryKey , nodeLocation ) ; if ( LOG . isDebugEnabled ( ) ) { LOG . debug ( "WComponent converted to reference. Ref = " + ref + ". Component = " + getClass ( ) . getName ( ) ) ; } return ref ; } else { LOG . debug ( "WComponent not accessible via the repository, so it will be serialised. Component = " + getClass ( ) . getName ( ) ) ; return this ; } }
Implement writeReplace so that on serialization WComponents that are registered in the UIRegistry write a reference to the registered component rather than the component itself . This ensures that on deserialization only one copy of the registered component will be present in the VM .