[SOLVED] Groovy dynamic object properties from string get and set

If you need to evaluate some properties of an object from strings like:

person is

class Person {
  Name name
class Name {
  String first
  String second


	def evalProperty(object, String property) {
	  Eval.x(object, 'x.' + property)

And the setter 🙂

	void setProperty(Object object, String propertyPath, Object value) {
		def pathElements = propertyPath.tokenize('.')
		Object parent = evalProperty(object, pathElements[0..-2].join('.'))
		parent[pathElements[-1]] = value


evalProperty(person, 'name.first')
setProperty(person,'name.first','New Name')

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s