开发者

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. 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技巧java:599)

I am using groovy 1.8.0


You need to return the template itself from the with block:

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.

I suspect your error is caused by oapTxId being of type MyXMLTemplate, and so not assignable from String.

Incidetally, as your with block is just initializing class properties, you could use the more idiomatic constructor and setters approach:

MyXmlTemplate template = new MyXMLTemplate(TxId: 'mnop', oapTxId : 'abcd')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜