为什么这个Groovy代码试图投射?

时间:2013-09-10 08:49:51

标签: groovy

我在“handDetailList.each”行抛出了一个强制转换异常。我不明白为什么我的代码试图将列表转换为“手”类?在我看来,有时Groovy用铸造做奇怪的事情......?

private Hand buildHands(List handDetailList) {

        def parsedHand = new Hand()

        parsedHand.setTableName(handDetailList.get(1))


        handDetailList.each {

        }
    }

我得到以下异常(我编辑了异常,第70行是“handDetailList.each {”):

Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object <details of the list, omitted> with class 'java.util.ArrayList' to class 'gameMechanics.Hand' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: gameMechanics.Hand(java.lang.String,........


    at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:358)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:599)
    at advisor.HistoryParser.buildHands(HistoryParser.groovy:70)
    at advisor.HistoryParser.this$2$buildHands(HistoryParser.groovy)
    at advisor.HistoryParser$this$2$buildHands.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at advisor.HistoryParser.parse(HistoryParser.groovy:57)
    at advisor.HistoryParser$parse.call(Unknown Source)

1 个答案:

答案 0 :(得分:4)

each会返回each被调用的列表。

您已经说过该函数返回类型为Hand的对象,并且由于Groovy会自动返回方法中的最后一个语句,它会尝试将列表转换为Hand的实例并失败。 ..

你想回来的是什么? parsedHand变量?

也许试试:

private Hand buildHands(List handDetailList) {
    def parsedHand = new Hand()
    parsedHand.setTableName(handDetailList.get(1))
    handDetailList.each {
    }
    parsedHand
}

如果是的话。