Add a script to handle the multiplicity

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:

  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.Property in the Type field.
  5. Type javaType in the Name field.
  6. Click MQL in the Language group.

  7. Click Finish.

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:

  1. If the isMultivalued() method answers true, the String "java.util.Collection" is returned.
  2. Otherwise the expression 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}).

Related reference
method call
default value expression
null management