[英]Creation of an instance with `with` block causes a type issue
I am using Groovy to create a package that I use in ReadyApi.我正在使用 Groovy 创建我在 ReadyApi 中使用的 package。
In a Groovy script test step, I do the following:在 Groovy 脚本测试步骤中,我执行以下操作:
class B {
String value
boolean isSomething
}
class A {
String name
B propB
public A() {
this.name = "Maydan"
}
}
def x = (A) new A().with { propB = new B(value: "Abc", isSomething: true) }
And I get the following error:我收到以下错误:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'B@6c218cea' with class 'B' to class 'A' error at line: 15
org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将 object 'B@6c218cea' 与 class 'B' 转换为 class 'A' 行错误:15
Does someone know why?有人知道为什么吗? It doesn't make any sense to me.
这对我来说没有任何意义。
Kind regards.亲切的问候。
PS: I would like to create an instance of class A (by using its parameterless constructor) and setting its field propB in a single statement PS:我想创建一个 class A 的实例(通过使用其无参数构造函数)并在单个语句中设置其字段 propB
You need to return your A
object from the .with
closure.您需要从
.with
闭包中返回A
object。 You may do it like that:你可以这样做:
def x = (A) new A().with { propB = new B(value: "Abc", isSomething: true); return it}
but to me personally it looks a little bit odd.但就我个人而言,它看起来有点奇怪。 I would do it like that:
我会这样做:
def x = new A(propB: new B(value: "Abc", isSomething: true))
The same effect, but more compact and readable.相同的效果,但更紧凑和可读。 It doesn't require to change your
A
and B
definitions, this "map constructor" works out of the box in Groovy, it will call your parameterless constructor and then assigns the necessary fields ( propB
in your case).它不需要更改您的
A
和B
定义,这个“地图构造函数”在 Groovy 中开箱即用,它将调用您的无参数构造函数,然后分配必要的字段(在您的情况下为propB
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.