Now we want to generate a Java method for each operation defined on a UML Class:
You can see the Class Order
has an operation findLineItem
linked through the reference ownedOperation
.
Create a script to implement a Java method declaration:
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 } }