我正在做一些粗略的事情,比如使用Groovy的metaClass和Eval从XML导入动态地为对象分配属性:
class ObjectBuilder {
def assignProp(String propName, String propValue) {
Eval.x(this, "x.metaClass.${propName} = '${propValue}'")
}
}
def h = new ObjectBuilder()
h.assignProp('name', 'Henson')
println(h.name)
我想做的是,能够在其内部实例化该类的另一个副本:
Eval.x(this, "x.metaClass.${ObjName} = new ObjectBuilder()")
但是我不能,因为我认为这个类没有传递给绑定。还有其他解决方案吗?
答案 0 :(得分:2)
一些解决方案:
您可以尝试使用一堆Expandos
:
h = new Expando()
h.last = new Expando()
h.last.name = 'tech'
assert h.last.name == 'tech'
xml = '''
<person>
<name>john</name>
<surname>doe</surname>
<age>41</age>
<location>St Louis, MO</location>
</person>
'''
class Person {
def name, surname, location, age
}
root = new XmlParser().parseText xml
person = new Person(root.children().collectEntries { [it.name(), it.text()] })
person.metaClass.getFullname = { "$delegate.name $delegate.surname" }
assert person.fullname == "john doe"
person.metaClass.likes = "chicken with lemon"
assert person.likes == "chicken with lemon"
map = [:]
map.last = [:]
map.last.name = 'Tech'
assert map.last.name == 'Tech'
答案 1 :(得分:1)
传递一个新实例化的对象,然后使用Eval分配它似乎有效:
class ObjectBuilder {
def assignProp(String propName, String propValue) {
Eval.x(this, "x.metaClass.${propName} = '${propValue}'")
}
def nestObj(String objName) {
Eval.xy(this, new ObjectBuilder(), "x.metaClass.${objName} = y")
}
}
ObjectBuilder h = new ObjectBuilder()
h.assignProp('name', 'Henson')
h.nestObj('last')
h.last.assignProp('name', 'Tech')
println h.name + ' ' + h.last.name