0

我正在做一些粗俗的事情,比如使用 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()")

但我不能,因为我认为这个类没有传递给绑定。还有其他解决方案吗?

4

2 回答 2

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'
于 2014-10-07T17:49:17.793 回答
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
于 2014-10-07T17:44:19.203 回答