Groovy和final属性如何用Map设置?

Mar*_*rco 3 grails groovy

我试图在Groovy源中设置最终属性(在Grails项目中使用)并遵循一些示例但不知何故我似乎无法工作,我无法找出原因..

class Foo {

  final x

  Foo(Map m=[:]) {
    m.each { key, value -> this.@"$key" = value }
  }
}

def foo = new Foo(x:1)
Run Code Online (Sandbox Code Playgroud)

我收到错误:

Cannot set the property 'x' because the backing field is final.

根据在互联网上发现的一些帖子,这应该工作.为什么失败怎么能在使用最终字段时通过地图设置属性?

win*_*n74 9

您可以使用@Immutable注释来实现所搜索的结果

@Immutable
class Foo {
  def x
}
Run Code Online (Sandbox Code Playgroud)

然后这可以称为

def foo = new Foo([:])
Run Code Online (Sandbox Code Playgroud)

要么

def foo = new Foo(x:42)
Run Code Online (Sandbox Code Playgroud)

然后是

foo.x = 43
Run Code Online (Sandbox Code Playgroud)

原因

ERROR groovy.lang.ReadOnlyPropertyException:
Cannot set readonly property: y for class: Foo
Run Code Online (Sandbox Code Playgroud)