[英]groovy “with” block usage query
I am trying to use the with block in Groovy to easily initalize my class, but I am getting the following error. 我试图在Groovy中使用with块轻松地初始化我的班级,但出现以下错误。 Could anyone tell me what I am doing wrong?
谁能告诉我我在做什么错?
MyXMLTemplate template = new MyXMLTemplate ().with {
TxId = 'mnop'
oapTxId = 'abcd'
}
The error I get is: 我得到的错误是:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'abcd' with class 'java.lang.String' to class 'org.example.MyXMLTemplate'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:331)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:599)
I am using groovy 1.8.0 我正在使用groovy 1.8.0
You need to return the template itself from the with
block: 您需要从
with
块返回模板本身:
MyXMLTemplate template = new MyXMLTemplate ().with {
TxId = 'mnop'
oapTxId = 'abcd'
it
}
It's hard to see what the problem is without seeing the definition of your class. 如果不查看类的定义,很难知道问题出在哪里。 I'll assume that
TxId
and oapTxId
are both properties of the class. 我假设
TxId
和oapTxId
都是该类的属性。
I suspect your error is caused by oapTxId
being of type MyXMLTemplate
, and so not assignable from String. 我怀疑你的错误是造成
oapTxId
是类型MyXMLTemplate
,所以不从字符串分配。
Incidetally, as your with
block is just initializing class properties, you could use the more idiomatic constructor and setters approach: 附带地,由于
with
块只是初始化类属性,因此可以使用更惯用的构造函数和设置方法:
MyXmlTemplate template = new MyXMLTemplate(TxId: 'mnop', oapTxId : 'abcd')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.