Description
Added an AST transformation @PojoBuilder that creates for given provided Pojo builder class "with" methods that allow to set values on a Pojo together with the "build" method that allows to instantiate it.
Example:
POJO - Person
class Person { String firstName String surName }
PersonBuilder
@PojoBuilder(forClass = Person)
class PersonBuilder {
}
Building
def person = personBuilder.withFirstName("Robert").withSurName("Lewandowski").build()
Verification
assert person.firstName == "Robert" assert person.surName == "Lewandowski"
Also added building with validation closure:
try { def person = personBuilder.withFirstName("Robert").build { if (it.surName == null ){ throw new IllegalStateException() } } fail("should fail due to validation closure") } catch(Exception exception ) { }
Possible extensions:
- Not only for POJOs - for other classes too (right now the object is constructed by picking the default constructor - it can be changed by picking the largest constructor and basing on the types, names etc. create proper "with" methods
- A "withCustomLogic" method that takes a closure as argument and performs custom logic on object to be built
- ImmutableBuilder that at each "with" method creates a new builder instead of setting values on itself
Pull request: https://github.com/groovy/groovy-core/pull/341