我试图在Groovy中使用with块轻松地初始化我的类(class),但是出现以下错误。谁能告诉我我在做什么错?
MyXMLTemplate template = new MyXMLTemplate ().with {
TxId = 'mnop'
oapTxId = 'abcd'
}
我得到的错误是:
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)
我正在使用groovy 1.8.0
最佳答案
您需要从with
块返回模板本身:
MyXMLTemplate template = new MyXMLTemplate ().with {
TxId = 'mnop'
oapTxId = 'abcd'
it
}
关于groovy "with" block 使用情况查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7344862/