In the previous step, we generated a Java field for each UML attribute, regardless of its multiplicity.
For example the UML Property items of the UML Class Order in the sample model has a multiplicity 0..*
.
Its corresponding Java field type should be java.util.Collection
, not LineItem
.
The type Property inherits from the type MultiplicityElement.
The Java class com.sodius.mdw.metamodel.uml21.MultiplicityElement
defines a method
isMultivalued()
, which determines if the upper bound is higher than 1
.
We have to update the generation to introduce an if
directive to test the isMultivalued()
method on each Property.
We could add this directive directly inside the text template, but because the text to generate depends on each Property
,
we will introduce a script to keep the template clear.
A script is a method dynamically added to a metatype.
To add a script:
A file uml21_Property.mqs
is created: it allows us
to define MQL scripts on the metatype UML Property.
Change its contents to:
package tutorial.java; metatype uml21.Property; public script javaType() : String { if (self.isMultivalued()) { return "java.util.Collection"; } else { // if the type is not set, returns "Object" return self.type.name ? "Object"; } }
The self variable is available in the script contents. This variable is the instance the script is evaluated on (instance of the script's metatype).
The script behavior is the following:
isMultivalued()
method answers true
, the String "java.util.Collection"
is returned.self.type.name
is evaluated.
The String "Object"
is returned if the type
reference returns null
,
due to the default value expression
and the null management of MDWorkbench.
Now the script javaType can be used in a text template,
as you do with any predefined feature of the type Property
(e.g. $(myProperty.javaType}
).