具有父类的groovy不可变对象
我有两个不可变的groovy类,它们有一些共享值,我正试图将它们抽象为父类。但是,当我创建以下内容时,第二个测试用例总是失败。尽管所有内容都正确编译并且在运行时不会抛出错误,但当我在构造函数中分配父属性时,它从未设置,从而导致空值。我还没有发现任何文件禁止这样做,但我想知道这是否可能?我尝试了许多注释和类类型的配置(例如,从父类中删除抽象),但除了完全删除具有父类的groovy不可变对象,groovy,abstract-class,immutability,Groovy,Abstract Class,Immutability,我有两个不可变的groovy类,它们有一些共享值,我正试图将它们抽象为父类。但是,当我创建以下内容时,第二个测试用例总是失败。尽管所有内容都正确编译并且在运行时不会抛出错误,但当我在构造函数中分配父属性时,它从未设置,从而导致空值。我还没有发现任何文件禁止这样做,但我想知道这是否可能?我尝试了许多注释和类类型的配置(例如,从父类中删除抽象),但除了完全删除@Immutable标记外,似乎没有什么效果 abstract class TestParent { String parent
@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
}
}
根据的代码,由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
我希望这会有所帮助:)