Grails accessing nested fields using gstrings

巧了我就是萌 提交于 2019-12-05 22:42:07

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"}

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}"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!