In Java 8 we can create a constructor reference. We must use the syntax Class::new
and we get a constructor reference. This syntax is not supported in Groovy, but we can use the method pointer or reference syntax .&
to turn a method into a closure. We can even turn a constructor into a closure and use it everywhere where closures are allowed.
In the following sample code we have a User
class with some properties. Via the User.metaClass
we can get a reference to the method invokeConstructor
and turn it into a method closure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | @groovy.transform.Immutable class User { String name int age } // Initial list with user defined // using a map or Object array. def userList = [ // User defined as map, keys // are properties of User class. [name: 'mrhaki' , age: 41 ], // Object array with name and // age properties for User class. [ 'john' , 30 ] as Object[] ] // Create constructor reference. // Result is a closure we can use in our code. def createUser = User.metaClass.&invokeConstructor // Invoke the collect method with our // constructor reference. At the end // all elements of the userList // are converted to new User objects. def users = userList. collect (createUser) assert users.name == [ 'mrhaki' , 'john' ] assert users.age == [ 41 , 30 ] |
Code written with Groovy 2.4.1.