Archive

Posts Tagged ‘tree’

Interesting serialization trick

juillet 24, 2009 1 commentaire

Wicket is a well known serialization addict, and as such it’s quite often a topic when dealing with wicket pages and, especially, going back through the page map.

In doing so, we had recently the following surprise : the DefaultMutableTreeNode, a javax.swing.tree class, is used to to the current incarnation of the tree component in wicket. We were wondering whether it would keep, or not, the user data put into it. A quick look gave us the following answer :

    /** optional user object */
    transient protected Object	userObject;

Quite plain isn’t it ? However, doing some more tests, we realized that the user data was in fact persisted… How comes ? Some more search and a second look at the DefaultMutableTreeNode class provided this answer :

    // Serialization support.
    private void writeObject(ObjectOutputStream s) throws IOException {
	Object[] tValues;

	s.defaultWriteObject();
	// Save the userObject, if its Serializable.
	if(userObject != null && userObject instanceof Serializable) {
	    tValues = new Object[2];
	    tValues[0] = "userObject";
	    tValues[1] = userObject;
	}
	else
	    tValues = new Object[0];
	s.writeObject(tValues);
    }

Surprising isn’t it ? A bit misleading maybe (for once a comment on the userObject might have been welcomed), but nice solution to serialize a class whose some content is unknown upfront ! I had never seen such a way to add objects to the serialized form ! Who knows, it might even come handy one day !

++

Publicités
Étiquettes : , , ,
%d blogueurs aiment cette page :