Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: Set dynamic nested method using string as path

Tags:

dynamic

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'

Returns a MissingFieldException.

Any hints?

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
  }
like image 999
Jim Gough Avatar asked Nov 13 '22 09:11

Jim Gough


1 Answers

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

like image 160
Dev Blanked Avatar answered Nov 15 '22 07:11

Dev Blanked