【问题标题】:Groovy: Set dynamic nested method using string as pathGroovy:使用字符串作为路径设置动态嵌套方法
【发布时间】:2013-03-26 15:57:56
【问题描述】:

我有一个对象中的对象的路径,我想使用 Groovy 的动态功能设置它。通常您只需执行以下操作即可:

class Foo {
  String bar
}


Foo foo = new Foo
foo."bar" = 'foobar'

这工作正常。但是如果你有嵌套对象呢?比如:

class Foo {
  Bar bar
}

class Bar {
  String setMe
}

现在我想使用动态设置,但是

Foo foo = new Foo()
foo."bar.setMe" = 'This is the string I set into Bar'

返回 MissingFieldException。

有什么提示吗?

更新:感谢 Tim 为我指明了正确的方向,那里的初始代码非常适合检索属性,但我需要使用路径字符串设置值。

这是我从蒂姆建议的页面中得出的结论:

  def getProperty(object, String propertyPath) {
    propertyPath.tokenize('.').inject object, {obj, prop ->
      obj[prop]
    }
  }

  void setProperty(Object object, String propertyPath, Object value) {
    def pathElements = propertyPath.tokenize('.')
    Object parent = getProperty(object, pathElements[0..-2].join('.'))
    parent[pathElements[-1]] = value
  }

【问题讨论】:

标签: dynamic groovy


【解决方案1】:

以下工作正常。

foo."bar"."setMe" = 'This is the string I set into Bar';

如果不覆盖 getProperty,您可以使用 GString 的“${}”语法获得相同的结果,如下代码所示

class Baz {
    String something
}

class Bar {

    Baz baz

}

class Foo {
    Bar bar
}

def foo = new Foo()
foo.bar = new Bar()
foo.bar.baz = new Baz()

def target = foo
def path = ["bar", "baz"]
for (value in path) {
    target = target."${value}"
}

target."something" = "someValue"
println foo.bar.baz.something

final println 按预期打印“someValue”

【讨论】:

  • 只是对这个优秀答案的一个小补充,以避免在这个问题上绊倒:您需要明确使用 double quotes 才能使其工作,因为 GStrings(其中包含表达式)是这样定义的.但我猜你们所有的 groovy 程序员都已经知道了 :)
猜你喜欢
  • 1970-01-01
  • 2012-03-26
  • 2019-08-27
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多