groovy groovy - 1 year ago 268
Groovy Question

Groovy object properties in map

Instead of having to declare all the properties in a map from an object like:

prop1: object.prop1


Can't you just drop the object in there like below somehow? Or what would be a proper way to achieve this?

results: [
object,
values: [
test: 'subject'
]
]

Answer Source

object.properties will give you a class as well

You should be able to do:

Given your POGO object:

class User {
    String name
    String email
}

def object = new User(name:'tim', email:'[email protected]')

Write a method to inspect the class and pull the non-synthetic properties from it:

def extractProperties(obj) {
    obj.getClass()
       .declaredFields
       .findAll { !it.synthetic }
       .collectEntries { field ->
           [field.name, obj."$field.name"]
       }
}

Then, map spread that into your result map:

def result = [
    value: true, 
    *:extractProperties(object)
]

To give you:

['value':true, 'name':'tim', 'email':'[email protected]']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download