オブジェクト内のオブジェクト内のオブジェクトへのパスがあり、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
}