class.tpl example

Code generation example

This example demonstrates how you could generate code based on a Java type. The example takes a Java class instance as input and generates a class declaration for that type. The class declaration does not include any fields or methods in this simple example, but it includes all the type modifiers and the super class and interfaces.

Let's take a look at the template first:


A few explanations about the template:

  • class is expected to represent a valid java.lang.Class instance.
  • the ${quiet} block allows us to make template variable assignments without having them appear in the output.
  • we use ${if} statements to conditionally include the declaration modifiers and inheritance relationships.
  • we use a ${foreach} statement to iterate over all implemented interface types. We are using the foreach.sep and foreach.suffix metadata to inject additional text into the loop.

The easiest way to experiment with this template is to use it from the terp command line utility. As the example expects a Java class instance to be bound to the variable named class, we have to use an -E switch to define the class variable.

C:\terp\bin>terp -Eclass=java.lang.String.class -f ..\doc\examples\template\class.tpl
${class=java.lang.String.class #quiet}${import('class.tpl')}C:\terp\bin>terp -Eclass=java.util.Hashtable.class -f ..\doc\examples\template\class.tpl
${class=java.util.Hashtable.class #quiet}${import('class.tpl')}C:\terp\bin>

While the above example uses a Java class instance as the information source, you could use any Java object as the source for the information that you wish to use to populate the template. You are of course not limited to generating Java code. The output is entirely defined by the template and by whatever information you include in your data model.

One last note: this page was generated using terp. We embedded the class.tpl contents after applying an xmlencode formatter to show the template source. Then we imported the template twice, each time with a different class definition preceding it. This is a nice example of how you can use terp to create documentation that is 100% in sync with your sample code.

Copyright 2006-${now['%tY']} by Codemesh, Inc., ALL RIGHTS RESERVED

code generation home expressions templates ant about us contact us download