3

I am trying to access a nested field using gstring but it throws exception groovy.lang.MissingPropertyException

I have two classes

Class Person{
   Address address
}
Class Address{
  String city
}

Somewhere in my code I am doing,

def person = Person.get(1)
def field = "address.city"
def city = person."${field}"

The line where I am trying to fetch city from person is throwing groovy.lang.MissingPropertyException

If I try to fetch a direct property using gstring it works but the above given code doesnt work.

Any help?

pikachu
  • 97
  • 1
  • 8

2 Answers2

12

What you're doing here is trying to access a property by name address.city which is equal to person."address.city", which means that the dot here gets considered as part of property name - not as access separator as you expect. The following code should resolve your property:

def city = field.tokenize('.').inject(person) {v, k -> v."$k"}
Nikita Volkov
  • 42,792
  • 11
  • 94
  • 169
3

I think that the problem is with dot operator for access to a subproperty.

This works:

class Person{
   String address
}

def person = new Person(address:'Madrid')

def field = 'address'
assert 'Madrid' == person."${field}"

This works:

class Person{
   Address address
}

class Address {
  String city
}

def person = new Person(address: new Address(city: 'Madrid'))

def field = 'address'
def subField = 'city'
assert 'Madrid' == person."${field}"."${subField}"
Arturo Herrero
  • 12,772
  • 11
  • 42
  • 73
  • 1
    While I agree that the other answer by Nikita Volkov, def city = field.tokenize('.').inject(person) {v, k -> v."$k"}, IS a VERY elegant answer, I prefer the simplicity and readability of this answer. At a glance, this answer is clearly understood. – TriumphST Mar 11 '16 at 00:38