【问题标题】:groovy immutable object with parent class具有父类的常规不可变对象
【发布时间】:2016-07-21 20:31:21
【问题描述】:

我有两个不可变的 groovy 类,它们有一些共享值,我试图将它们抽象为父类。但是,当我创建以下内容时,第二个测试用例总是失败。尽管一切都正确编译并且在运行时没有引发错误,但是当我将父属性分配给构造函数时,它永远不会被设置,从而导致空值。我还没有找到任何禁止这样做的文档,但我想知道这是否可能?我已经尝试了许多注释和类类型的配置(例如从父级中删除抽象),但除了完全删除 @Immutable 标记之外似乎没有任何工作。

abstract class TestParent {
       String parentProperty1
}

@ToString(includeNames = true)
@Immutable
class TestChild extends TestParent {
   String childProperty1
   String childProperty2
}


class TestCase {
    @Test
    void TestOne() {
        TestChild testChild = new TestChild(
                childProperty1: "childOne",
                childProperty2: "childTwo",
                parentProperty1: "parentOne"
        )

        assert testChild
        assert testChild.parentProperty1
    }
}

【问题讨论】:

    标签: groovy abstract-class immutability


    【解决方案1】:

    基于ImmutableASTTransformation的代码,createConstructorMapCommon方法添加的Map-arg构造函数在方法体中不包含对super(args)的调用。

    这意味着不可变类默认是自包含的

    现在,如果你想这样做,你需要使用组合而不是继承,这是你如何做到这一点的一个例子:

    import groovy.transform.*
    
    @TupleConstructor
    class A {
      String a
    }
    
    @Immutable(knownImmutableClasses=[A])
    class B {
      @Delegate A base
      String b
    }
    
    def b = new B(base: new A("a"), b: "b")
    assert b.a
    

    我希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-26
      • 1970-01-01
      相关资源
      最近更新 更多