Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails / Groovy - Domain Object - Map of its Properties

How can I get a map of the key/values of only the user-defined properties on one of my domain objects?

Problem is if I do this myself, I get my properties plus class, metaClass, constraints, closures, etc...

I assume Grails can do this fairly easily because it is done at some level in the scaffold code right? How can I do this myself?

like image 682
BuddyJoe Avatar asked Jun 14 '11 12:06

BuddyJoe


2 Answers

Try this

class Person{
    String name
    String address
}

def filtered = ['class', 'active', 'metaClass']

def alex = new Person(name:'alex', address:'my home')

def props = alex.properties.collect{it}.findAll{!filtered.contains(it.key)}

props.each{
    println it
}

It also works if you use alex.metaClass.surname = 'such'. This property will be displayed in the each loop

like image 186
Alex Such Avatar answered Nov 05 '22 20:11

Alex Such


This is an old question, but I just ran across this requirement and found another solution that is worth answering here for others who come across this thread. I have put together an example based on that thread:

Sample Bean

class SampleBean {

    long id
    private String firstName
    String lastName
    def email

    Map asMap() {
        this.class.declaredFields.findAll { !it.synthetic }.collectEntries {
            [ (it.name):this."$it.name" ]
        }
    }
}

Test Class

class Test {

    static main(args) {
        // test bean properties
        SampleBean sb = new SampleBean(1,'john','doe','[email protected]')

        println sb.asMap()
    }

}

The SampleBean I put a variety of fields to show that it works, this is the output of the println:

[id:1, firstName:john, lastName:doe, email:[email protected]]
like image 3
Hatem Jaber Avatar answered Nov 05 '22 21:11

Hatem Jaber