groovy groovy - 1 year ago 209
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: [
values: [
test: 'subject'

Answer Source 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) {
       .findAll { !it.synthetic }
       .collectEntries { field ->
           [, obj."$"]

Then, map spread that into your result map:

def result = [
    value: true, 

To give you:

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