Grails / Groovy - Domain Object - Map of its Properties

前端 未结 3 2032
无人及你
无人及你 2021-01-18 06:18

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

相关标签:
3条回答
  • 2021-01-18 06:43

    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','jd@gmail.com')
    
            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:jd@gmail.com]
    
    0 讨论(0)
  • 2021-01-18 07:03

    I think the best way is to use .properties on a domain object to get map of the fields in grails , tested in grails 2.1

    class Person{
    String firstName
    String lastName
    
    } 
    def person=new Person()
    person.firstName="spider"
    person.lastName="man"
    def personMap=person.properties 
    
    0 讨论(0)
  • 2021-01-18 07:04

    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

    0 讨论(0)
提交回复
热议问题