我不知道这在 Grails 中效果如何,但这在 Groovy 中有效:
class ObjectA {
String name
Object1 object1
Object2 object2
ObjectA(java.util.Map attrs) {
attrs.each { key, val ->
this.class.declaredFields.each {
if (!it.synthetic) {
def className = it.type.name.toLowerCase()
def localVar = it.name
if (key =~ /^${className}/) {
def realKey = key.replaceAll("^${className}", "")
if (!this."${localVar}") {
this."${localVar}" = Class.forName("${className.capitalize()}", true, this.class.classLoader).newInstance()
}
this."${localVar}"."${realKey}" = val.replaceAll("'", "")
} else {
try {
this."${key}" = val.replaceAll("'", "")
} catch (MissingPropertyException e) { }
}
}
}
}
}
}
class Object1 {
String foo
String bar
}
class Object2 {
String foo
String bar
}
def data = "name: 'dan', object1foo: 'food', object1bar: 'baz', object2foo: 'foor', object2bar: 'xanax'"
def attrs = data.split(',').inject([:]) { map, keyPair ->
keyPair.split(':').with { map[it[0].trim()] = it[1].trim() }
map
}
def a = new ObjectA(attrs)
assert a.name == 'dan'
assert a.object1 instanceof Object1
assert a.object2 instanceof Object2
assert a.object1.foo == 'food'
assert a.object2.foo == 'foor'
assert a.object1.bar == 'baz'
assert a.object2.bar == 'xanax'
希望能帮助到你。:-)