O'Reilly logo

Jakarta Commons Cookbook by Timothy M. O'Brien

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

4.10. Transforming Objects

Problem

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

Solution

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

Discussion

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required