简体   繁体   English

Groovy 3.0 中 object 字段访问的行为是否改变?

[英]Changed behavior in object field access in Groovy 3.0?

I've recently stumbled on this issue when assisting in the migration of some legacy code.我最近在协助迁移一些遗留代码时偶然发现了这个问题。

The following used to execute correctly in Groovy 2.4.x:以下用于在 Groovy 2.4.x 中正确执行:

class Person {
  String name
}

def me = new Person( name : 'Joe' )

assert me.(name) == 'Joe'

while it raises an exception when executed on Groovy 3.0.2:在 Groovy 3.0.2 上执行时会引发异常:

groovy.lang.MissingPropertyException: No such property: name for class: MyScript groovy.lang.MissingPropertyException:没有这样的属性:class 的名称:MyScript

Enclosing the property name in parentheses actually looks wrong to me: as a matter of fact, I was surprised that an exception was not raised in older releases too.将属性名称括在括号中对我来说实际上是错误的:事实上,我很惊讶在旧版本中也没有引发异常。

The syntax I would probably have used is either:我可能会使用的语法是:

assert me.name == 'Joe'

or something like:或类似的东西:

assert me.'name' == 'Joe'

which work in both versions 2.4 AND 3.0.它适用于 2.4 和 3.0 版本。

I did some research and couldn't find anything in the Changelogs from Groovy 2.4 through Groovy 3.0 that refers to something that could affect this behavior.我做了一些研究,在从 Groovy 2.4 到 Groovy 3.0 的变更日志中找不到任何涉及可能影响此行为的内容的内容。

Am I missing something here?我在这里错过了什么吗?

Was the fact that the code worked in 2.4 an unexpected behavior, which has been corrected?代码在 2.4 中工作的事实是否是一种意外行为,已得到纠正? Or is this actually expected to work?或者这实际上是否可行?

My guess is that it has to do with the switch to the new Parrot parser in version 3.0.我的猜测是它与在 3.0 版中切换到新的 Parrot 解析器有关。

Thanks!谢谢!

When you wrap the property name in parens, like "me.(name)", you are using dynamic property syntax.当您将属性名称包装在括号中时,例如“me.(name)”,您使用的是动态属性语法。 Groovy is supposed to resolve "name" in the enclosing scope and not against the receiver. Groovy 应该在封闭的 scope 中解析“名称”,而不是针对接收器。 If you want to get the "name" property from "me", you can write "me.name" or "me.'name'" or "me['name']" or "me.getProperty('name')".如果要从“me”中获取“name”属性,可以写成“me.name”或“me.'name'”或“me['name']”或“me.getProperty('name') ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM