Adding the cloning functionality to Groovy Beans
There are several strategies to clone an object in Java. To clone an object means the ability to create an object with the same state as the original object.
A widely used strategy to clone an object is for the class to be cloned to implement the Cloneable
interface, and implement a method, clone
, in which the cloning code is executed. Naturally, Groovy supports this semantic but makes it even easier to implement with the @AutoClone
annotation, which will be demonstrated in this recipe.
How to do it...
The following steps will show the power of the @AutoClone
annotation:
Let's define an object
Vehicle
and annotate the class with the@AutoClone
annotation:import groovy.transform.AutoClone @AutoClone class Vehicle { String brand String type Long wheelsNumber }
In the same script where the
Vehicle
object is defined, add the following code:def v1 = new Vehicle() v1.brand = 'Ferrari' v1.type = 'Testarossa' v1.wheelsNumber = 4 def v2 = v1.clone...