Groovy:@Immutable导致Setters

时间:2016-09-09 13:01:48

标签: groovy

我在使用@Immutability时遇到了麻烦(或者我感到困惑)。

鉴于此课程:

@Immutable
class TestField {
   String key
}

我希望我无法在像以下的实例上设置密钥:

class TestFieldSpec extends Specification {

    def 'do stuff'() {
        when:
        def t = new TestField('a')
        println t

        t.key = 'b'
        println t

        then:
        t
    }
}

但是,当我运行测试时,我看不到ReadOnlyPropertyException

Running TestFieldSpec
TestField(a)
TestField(b)

我使用 groovy-eclipse-compiler gmaven-plus Maven 一起使用。 Groovy版本 2.4.7

如果我在两者创建的类文件上运行 javap ,我会看到:

public final void setKey(java.lang.String);

但是,当我在 GroovyConsole 中执行相同操作时,事情就会发挥作用。

@groovy.transform.Immutable
class TestField {
    String key
}

def f = new TestField('a')
f.key = 'b'

产地:

抛出异常

groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: key for class: TestField
    at TestField.setProperty(ConsoleScript1)
    at ConsoleScript1.run(ConsoleScript1:7)

Groovy AST浏览器中,在阶段 终结,我看不到设置器。

非常感谢任何见解。 谢谢!

0 个答案:

没有答案
相关问题