5.7 Callback Parameter Type Conversion

The deferrable callback examples previously presented all make the assumption that while callbacks may modify the callback data, the callback parameter type remains fixed. This has helped to simplify the initial examples, but it does not reflect the more realistic situation where callback handlers will typically transform callback parameters from one type to another.

Callback parameter type conversion is expressed in the deferrable interface definition given in Listing 5.3 by the two Java generics <T> and <U>. The generic type <T> identifies the type of the callback parameter which is passed into the deferrable callback handler, while the generic type <U> identifies the data type which is returned by the callback handler on completion. As an example, Listing 5.14 shows a deferrable callback handler which converts an input of type Integer to an output of type String.


\begin{listing}
% latex2html id marker 1299\begin{small}
\begin{verbatim}pub...
...d{small}\caption{Deferrable Callback Handler With Type Conversion}
\end{listing}

The deferred event interface presented in Listing 5.2 is also parameterised by the generic type <T>, which in this case specifies the data type which will be output by the previous stage of the callback chain. Therefore when appending deferrable callback objects to a deferred event object, the generic type <T> of the deferrable callback input must match the generic type <T> specified for the deferred event object. This means that in the case of the example shown in Listing 5.14, the deferrable callback object may only be added to a deferred event object whose complete type specification is Deferred<Integer>.

When a new deferrable callback is added to the callback chain of a deferred event object, it modifies the generic type of the deferred event object to match the output type of the deferrable callback. This is carried out automatically by the addDeferrable method, which returns a new reference to the deferred event object with suitable type casting applied.


\begin{listing}
% latex2html id marker 1314\begin{small}
\begin{verbatim}......
...d{small}\caption{Adding Deferrable Callbacks With Type Conversion}
\end{listing}

Listing 5.15 shows the way in which type conversion may be applied to a deferred event object. The initial reference to the deferred event object (deferredInteger) is returned on starting a new long running task that will pass up an integer result on completion. When the deferrable callback object given in Listing 5.14 is added to the callback chain, a new reference to the deferred event object (deferredString) is automatically created with the correct type specification. This new reference may then be used to append another deferrable callback object, which in this case will accept a Java string object as its input. The full implementation of this example is present in the deferred examples package as DeferredChainExample3.