Protect hand-written user code

The UML model defines only the specification of operations, the developer must implement the corresponding Java methods by hand. When the code is regenerated, this hand-written code must be preserved. This is done using protected tags.

Change the script declaration on uml21.Operation to:

[#package tutorial.java]

[#metatype uml21.Operation]

[#script public declaration]
    [#set parameters = self.inParameters.concat("declaration", ", ")]
    public ${self.returnType.name} ${self.name}(${parameters}) {
        [#protectedStartTag]// Start of user code of ${self.name}()[/#protectedStartTag]
        return null; // TODO insert your code here
        [#protectedEndTag]// End of user code[/#protectedEndTag]
    }
    
[/#script]

The default code between the protected start and end tag directives ("return null; // TODO insert your code here") will be printed for the first generation only, when the generated file does not already exist. For subsequent generations, this default code will be ignored and replaced by the user code found in the existing file.

To see protected tags in action:

  1. Relaunch the generation and open the file Order.java. Its contents should be:

    public abstract class Order {
    
        private String date;
        private LineItem items;
        private Customer customer;
    
        public LineItem findLineItem(String productName) {
            // Start of user code of findLineItem()
            return null; // TODO insert your code here
            // End of user code
        }
    }
    
  2. Change the findLineItem implementation to:

        public LineItem findLineItem(String productName) {
            // Start of user code of findLineItem()
            throw new RuntimeException("No such product: " + productName);
            // End of user code
        }
    
  3. Relaunch the generation again. The contents of the file Order.java should stay the same, the findLineItem implementation is preserved.

Note: this example protected section is not very robust, as it is based on the operation name. If the operation is renamed, the corresponding protected user code is lost. A real world protected section should be based on an identifier constant in time.

Related reference
protected tags