You can use the InvokeHelper category and setProperties , here is a short example:
import groovy.transform.EqualsAndHashCode import groovy.transform.ToString import org.codehaus.groovy.runtime.InvokerHelper @EqualsAndHashCode @ToString class Address { String street String number String city } Address mainAddress = new Address(street: 'Test', number: '2B', city: 'London') use InvokerHelper, { mainAddress.setProperties([street: 'Lorem', number: 'Ipsum']) } assert mainAddress.street == 'Lorem' assert mainAddress.number == 'Ipsum' assert mainAddress.city == 'London'
Although, if you can avoid the modified objects, this is best for you. Otherwise, you need to think about thread safety so as not to run into concurrency issues. You can use the previous example to create a static method that expects 2 arguments: an existing object and a property map for updating. As a result, you get a new instance containing the updated fields. You can also make your class immutable.
source share