Grails 使用 gstring 访问嵌套字段

发布于 2024-12-10 17:33:00 字数 446 浏览 1 评论 0原文

我正在尝试使用 gstring 访问嵌套字段,但它抛出异常 groovy.lang.MissingPropertyException

我有两个类

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

在我正在执行的代码中的某个位置,

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

我尝试从 person 获取城市的行抛出 groovy.lang.MissingPropertyException

如果我尝试使用 gstring 获取直接属性,它可以工作,但上面给出的代码不起作用。

有什么帮助吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

信愁 2024-12-17 17:33:00

您在这里所做的是尝试通过名称 address.city 访问属性,该属性等于 person."address.city",这意味着这里的点得到被视为属性名称的一部分 - 而不是您期望的访问分隔符。以下代码应该可以解析您的属性:

def city = field.tokenize('.').inject(person) {v, k -> v."$k"}

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"}
梦屿孤独相伴 2024-12-17 17:33:00

我认为问题在于访问子属性的点运算符。

这有效:

class Person{
   String address
}

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

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

这有效:

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

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}"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文