Add methods declaration

Now we want to generate a Java method for each operation 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 Class Order has an operation findLineItem linked through the reference ownedOperation.

Create a script to implement a Java method declaration:

  1. Click File > New > Script.
  2. Type com.sodius.mdw.samples.tutorial/src in the Source folder field.
  3. Type tutorial.java in the Package field.
  4. Type uml21.Operation in the Type field.
  5. Type declaration in the Name field.
  6. Click Text in the Language group.

  7. Click Finish.

A file uml21_Operation.tgs is created: it allows us to define TGL scripts on the metatype UML Operation. Change its contents to:

[#package tutorial.java]

[#metatype uml21.Operation]

[#script public declaration]
    public Object ${self.name}() {
        return null; // TODO insert your code here
    }
    
[/#script]

The text template has to iterate on the ownedOperation list and print the corresponding Java method 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.javaType} ${attr.name};
[/#foreach]

[#-- Operations declaration --]
[#foreach operation : uml21.Operation in class.ownedOperation]
    ${operation.declaration}[#trim]
[/#foreach]
}
[/#template]

The template loops on each operation and calls the script declaration. The trim directive instructs the template rendering engine to ignore whitespaces in the directive line: ignore spaces and the line feed. It allows you to build a readable template without impacting the generated code. See Whitespace handling for more information.

Relaunch the generation and open the file Order.java:

public abstract class Order {

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

    public Object findLineItem() {
        return null; // TODO insert your code here
    }
    
}

Related reference
Whitespace handling
foreach directive
trim directive