Groovy: Set dynamic nested method using string as path

后端 未结 1 911
被撕碎了的回忆
被撕碎了的回忆 2021-01-19 01:30

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:

相关标签:
1条回答
  • 2021-01-19 01:43

    Following works correctly.

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

    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 prints "someValue" as expected

    0 讨论(0)
提交回复
热议问题