如何获得我域对象之一的用户定义属性的键/值的映射?Grails/Groovy - 域对象 - 其属性的映射
问题是,如果我这样做我自己,我让我的属性加类,元类的限制,封锁,等等
我认为Grails能够在一定程度上做到这一点很容易,因为它是做脚手架代码是否正确?我怎么能自己做这个?
如何获得我域对象之一的用户定义属性的键/值的映射?Grails/Groovy - 域对象 - 其属性的映射
问题是,如果我这样做我自己,我让我的属性加类,元类的限制,封锁,等等
我认为Grails能够在一定程度上做到这一点很容易,因为它是做脚手架代码是否正确?我怎么能自己做这个?
试试这个
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
}
如果使用alex.metaClass.surname = 'such'
它也适用。此属性将显示在每个循环
这适用于普通的groovy类,但对grails域对象并不那么简洁,因为grails域对象有额外的魔术缠绕在它们周围,也会被打印。 – krock 2016-04-08 01:21:13
这是一个老问题,但我只是碰到这种要求跑,发现another solution是值得在这里回答为别人谁遇到这个线程。我已经把基于该线程的例子:
样品豆
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" ]
}
}
}
测试类
class Test {
static main(args) {
// test bean properties
SampleBean sb = new SampleBean(1,'john','doe','[email protected]')
println sb.asMap()
}
}
的SampleBean
我把各种领域,以表明它的工作原理,这是println的输出:
[id:1, firstName:john, lastName:doe, email:[email protected]]
这适用于普通的groovy类,但对于grails域对象并不那么整洁,因为grails域对象有额外的魔术缠绕在它们周围,也会被打印出来。 – krock 2016-04-08 01:21:01
这是你在追求什么? http://stackoverflow.com/questions/4555150/gorm-persistent-properties – 2011-06-14 12:30:18
这正是我要建议的。显然,你必须小心瞬态属性。 – 2011-06-14 20:37:22