Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Use Constructor as Method Pointer

DZone's Guide to

Groovy Goodness: Use Constructor as Method Pointer

· Java Zone
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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 methodinvokeConstructor and turn it into a method closure:

@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.


Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}