4.10. Transforming Objects


You need to perform a transformation, taking an object and creating a new object.


Implement the Transformer interface. A Transformer takes an object and returns a new object instance. The following example demonstrates the joinArmy Transformer; the transform( ) method takes a Recruit object instance and returns a Soldier object:

import org.apache.commons.collections.Transformer;

Transformer joinArmy = new Transformer( ) {
    public Object transform(Object input) {
                Recruit recruit = (Recruit) input;
         BootCamp.obstacleCourse( recruit );
                Soldier soldier = BootCamp.graduate( recruit );

Recruit recruit1 = new Recruit("Pat T.");
System.out.println( "Status before transformation: " + recruit );

Soldier soldier1 = (Soldier) joinArmy.transform( recruit1 );
System.out.println( "Status after transformation: " + soldier );

A Recruit object is passed to the joinArmy.transform( ) method, and a Soldier object is returned. The state of the recruit and soldier instances are printed before and after the transformation:

Status before transformation: Pat T., Recruit
Status after transformation: Pat T., Soldier


This object isolates and encapsulates a transition; a system that needs to translate between two domain models or two object types should encapsulate such a transition in a Transformer. Transformer may be something of a misnomer. When an object undergoes a transformation, it is common to think of an object being modified or acted upon, but this is contrary to the design of the Transformer interface. The Javadoc for Transformer expressly states, “The original object is left unchanged.” Figure 4-3 illustrates the simple joinArmy Transformer.

Diagram of the joinArmy Transformer

Figure 4-3. Diagram of the joinArmy Transformer

See Also

Jakarta Commons Functor in the Commons Sandbox expands on the initial functors introduced in Commons Collections, introducing a UnaryFunction object that provides a simple interface equivalent to Transformer. For more information about UnaryFunction, see the Commons Functor page at http://jakarta.apache.org/commons/sandbox/functor.

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.