2013-03-19 7 views
5

オブジェクト内のオブジェクト内のオブジェクトのパスがあり、Groovyの動的能力を使用して設定したい。通常は次のようにするだけです: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 
    } 
+1

HTTPなど

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 

最終のprintlnプリント "someValueの" を示していて、あなたがGストリングのための "$ {}" 構文を使用して同じ結果を得ることができます上書きせずに

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

: //stackoverflow.com/questions/5488689/how-to-retrieve-nested-properties-in-groovy –

+0

getPropertyメソッドをビルドして使用してタスクを達成することができました。私は、コメントセクションはコードを配置するのはあまり良くありません –

答えて

1

:ここ

は、私はティムが提案ページから思い付いたものです。 getPropertyメソッドは以下のコードは期待

+1

他の人がこの問題に遭遇するのを避けるために、この優れた答えにちょっと追加しました。GString(式が内部にある)がそのように定義されているので、これを動作させるには二重引用符を明示的に使用する必要があります。しかし、私はあなたのグルーヴィープログラマがすでに知っていたと思う:) – kaskelotti

関連する問題