MyArchiBook

Archive for October 2013

@Canonical = @ToString + @TupleConstructor + @EqualsAndHashCode

with 3 comments

ToString in Groovy:

In Java , we override toString() to print results.

In Groovy, this can be achieved simply, by using the @ToString annotation which is one of the A.S.T Transformation traits.(Example given below)

Tuple Constructor:

import groovy.transform.ToString

@ToString
class Car{
  Long carID
  String carBrand
  String carModelNo
}

Car car=new Car(carID:10,carBrand:"Audi",carModelNo:"Q5")
println car                                      // O/P: Car(10, Audi, Q5)
car.carID=1
println car                                      // O/P: Car(1, Audi, Q5)
car.setCarID(4)
println car                                      // O/P: Car(4, Audi, Q5)

In a POGO class, the values to the atributes can be set in the above following ways,

  • Using a default constructor, where the attribute and its value is set as Key-Value pairs.
  • By creating a reference for the class and just denoting ref.attributeName=value
  • Setting values using Setter method.

However, values can also be set using Tuple Constructor like the example below,

import groovy.transform.ToString
import groovy.transform.TupleConstructor

@ToString
@TupleConstructor
class Car{
  Long carID
  String carBrand
  String carModelNo
}

Car car=new Car(15,"BENZ","E-63")
println car                       //O/P:Car(15, BENZ, E-63)

Here , the attribute key is not required. Only values are set directly.

NOTE: Values have to be set only in the order of the attributes listed in the POGO because this Tuple Constructor is a specific positional type Constructor.

The above 2 functionalities i.e., pretty print using toString() and assigning values using Tuple Constructor, along with Equals and HashCode check can be achieved by using a single annotation @Canonical which is imported from groovy.transform.Canonical

Therefore,

       @Canonical =  @ToString + @TupleCOnstructor + @EqualandHashCode

Have a great day 🙂

Advertisements

Written by thangaveluaishwarya

October 19, 2013 at 12:22 PM