1.7 Using Java Generics For Type Safety

One thing that is noticeable about the basic interface definitions previously presented is that many of them pass an arbitrary data parameter which uses the Java root object type, Object. This is because the Reaction framework treats all internal event data as opaque, arbitrary objects. This may seem to be an anathema in the context of a strongly statically typed language such as Java, but there are valid reasons for making this design decision.

A key property of the Reaction framework is that it allows for the run-time dynamic configuration of program flow by attaching and triggering callbacks. This dynamic behaviour means that the Reaction framework has no a-priori information about the parameter data types to be used for these callbacks - and the only reasonable assumption to make is that they are all subclassed from the common Java root object type.

Even though all callback parameter data is internally treated as arbitrary opaque objects, type safety may be restored at the interfaces by making use of Java generics. An example of the use of Java generics to enforce type safety on a timeable interface is shown in Listing 1.7.


\begin{listing}
% latex2html id marker 162\begin{small}
\begin{verbatim}publ...
...atim}
\end{small}\caption{Type Safe Timeable Interface Definition}
\end{listing}

The type safe implementation of the interface parameterises the basic version shown in Listing 1.6 by the addition of the generic type specifier <T>. This enforces a compile time constraint on the interface, such that only objects of type T may be passed to the onTick callback method. All the basic interface specifications previously presented in this introduction will adopt similar type parameterisation in order to enforce type safety throughout the Reaction framework.