Add fields declaration

Now we want to generate a Java field for each attribute defined on a UML Class:

  1. Open the model product21.xmi.
  2. Select the type Class.
  3. Select the Class Order and show its children.

You can see the attributes are linked to their class with the reference attribute. The text template has to iterate on the attribute list and print the corresponding Java field declaration:

[#package tutorial.java]

[#template public JavaSource(class : uml21.Class)]
[#file]generated/${class.name}.java[/#file]
public [#if class.isAbstract]abstract [/#if]class ${class.name} {

[#-- Attributes declaration --]
[#foreach attr : uml21.Property in class.attribute]
    private ${attr.type.name} ${attr.name};
[/#foreach]
}
[/#template]

The template loops on each attribute and prints the name of its type (dynamic text ${attr.type.name}) followed by its name.

[#-- Attributes declaration --] is a comment. A comment is delimited by [#-- and --] and is not written to the output. Note that thanks to automatic whitespace stripping, whitespaces and linefeeds on line containing only directives and comments are ignored.

Relaunch the generation and open the file Order.java:

public abstract class Order {

    private String date;
    private LineItem items;
    private Customer customer;
}

Related reference
foreach directive
Whitespace handling