Grails 使用 gstring 访问嵌套字段
我正在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在这里所做的是尝试通过名称
address.city
访问属性,该属性等于person."address.city"
,这意味着这里的点得到被视为属性名称的一部分 - 而不是您期望的访问分隔符。以下代码应该可以解析您的属性:What you're doing here is trying to access a property by name
address.city
which is equal toperson."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:我认为问题在于访问子属性的点运算符。
这有效:
这有效:
I think that the problem is with dot operator for access to a subproperty.
This works:
This works: