Groovy:使用字符串作为路径设置动态嵌套方法 [英] Groovy: Set dynamic nested method using string as path
问题描述
我有一个对象内的对象的路径,我想使用Groovy的动态能力进行设置。通常你可以这样做:
I have a path for an object within an object within an object and I want to set it using Groovy's dynamic abilities. Usually you can do so just by doing the following:
class Foo {
String bar
}
Foo foo = new Foo
foo."bar" = 'foobar'
可以正常工作。但是如果你有嵌套对象呢?如下:
That works OK. But what if you have nested objects? Something like:
class Foo {
Bar bar
}
class Bar {
String setMe
}
现在我想使用动态设置,但是
Now I want to use the dynamic setting, but
Foo foo = new Foo()
foo."bar.setMe" = 'This is the string I set into Bar'
返回MissingFieldException。
Returns a MissingFieldException.
任何提示?
更新:感谢Tim指出正确的方向,那里的初始代码在检索属性方面非常有用,但是我需要使用路径字符串设置值。
UPDATE: Thanks to Tim for pointing me in the right direction, the initial code on there works great at retrieving a property, but I need to set the value using the path string.
这是我从页面提出的建议:
Here's what I came up with from the page Tim suggested:
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
}
推荐答案
以下工作正常。
foo."bar"."setMe" = 'This is the string I set into Bar';
没有getProperty覆盖,您可以使用GString的$ {}语法来实现相同的结果,如下所示代码演示
Without getProperty overriding you can achieve the same result using "${}" syntax for GString as the below code demonstrates
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
final println prints "someValue" as expected
这篇关于Groovy:使用字符串作为路径设置动态嵌套方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!