Groovy has many AST annotations that add code to our class (the Abstract Syntax Tree - AST) before it is compiled. So the compiled class file contains the code added by the AST annotation. With the @AutoClone annotation, a clone method is added and the class implements the Cloneable interface. We have different strategies to choose from to support cloning for our class.

The default strategy is to invoke super.clone() in the generated clone method. The next statements will deep copy the properties (and optional fields) from our class. If one of the properties cannot be cloned, an exception is thrown. In the following example code snippet, we apply the @AutoClone annotation to the classes Course and Teacher:

To include fields as well as properties, we must set the annotation attribute includeFields to true.

If we want to invoke the default constructor of our class in the clone method, we must use the clone style AutoCloneStyle.SIMPLE. In the generated clone method, the constructor is invoked followed by copying the properties:

The last clone style we can choose is AutoCloneStyle.COPY_CONSTRUCTOR. This time, the annotation will add a protected constructor that takes another object of the same type as argument. This new constructor is used in the generated clone method. This style is useful if we have final read-only properties that can only be set via the constructor: