groovy 具有父对象的不可变对象 class
groovy immutable object with parent class
我有两个不可变的 groovy classes,它们有一些共享值,我试图将它们抽象到父 class。但是,当我创建以下内容时,第二个测试用例总是失败。虽然一切都正确编译并且在运行时没有抛出错误,但是当我分配父 属性 int 构造函数时,它永远不会设置,导致空值。我还没有找到任何禁止这样做的文件,但我想知道这是否可能?我已经尝试了一些注释和 class 类型的配置(例如,从父级中删除摘要)但是除了完全删除 @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
}
}
基于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
我希望这会有所帮助:)
我有两个不可变的 groovy classes,它们有一些共享值,我试图将它们抽象到父 class。但是,当我创建以下内容时,第二个测试用例总是失败。虽然一切都正确编译并且在运行时没有抛出错误,但是当我分配父 属性 int 构造函数时,它永远不会设置,导致空值。我还没有找到任何禁止这样做的文件,但我想知道这是否可能?我已经尝试了一些注释和 class 类型的配置(例如,从父级中删除摘要)但是除了完全删除 @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
}
}
基于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
我希望这会有所帮助:)