我有一个对象内对象的路径,我想使用Groovy的动态能力来设置它.通常只需执行以下操作即可:
class Foo {
String bar
}
Foo foo = new Foo
foo."bar" = 'foobar'
Run Code Online (Sandbox Code Playgroud)
这很好用.但是如果你有嵌套对象怎么办?就像是:
class Foo {
Bar bar
}
class Bar {
String setMe
}
Run Code Online (Sandbox Code Playgroud)
现在我想使用动态设置,但是
Foo foo = new Foo()
foo."bar.setMe" = 'This is the string I set into Bar'
Run Code Online (Sandbox Code Playgroud)
返回MissingFieldException.
任何提示?
更新:感谢Tim指出我正确的方向,那里的初始代码非常适合检索属性,但我需要使用路径字符串设置值.
这是我从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
}
Run Code Online (Sandbox Code Playgroud)
以下工作正常。
foo."bar"."setMe" = 'This is the string I set into Bar';
Run Code Online (Sandbox Code Playgroud)
如果不覆盖 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
Run Code Online (Sandbox Code Playgroud)
最终 println 按预期打印“someValue”
| 归档时间: |
|
| 查看次数: |
1817 次 |
| 最近记录: |