Grails / Groovy - Domain object - Map of its properties

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

The problem is that I do it myself, get my properties plus a class, metaClass, restrictions, closure, etc.

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

+7
source share
2 answers

try it

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 each cycle.

+8
source

This is an old question, but I just ran into this requirement and found another solution that is worth answering here to those who are faced with this thread. I put together an example based on this thread:

Bean example

 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" ] } } } 

Testing class

 class Test { static main(args) { // test bean properties SampleBean sb = new SampleBean(1,'john','doe',' jd@gmail.com ') println sb.asMap() } } 

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

 [id:1, firstName:john, lastName:doe, email: jd@gmail.com ] 
+3
source

All Articles