3

我有以下方法,其中我List<ImField>使用List<GPathResult> filteredList. 我执行filteredList.each闭包,在运行时生成类并为其分配静态类型ImField.

static List<ImField> getFields(GPathResult root,String fieldClass, String fieldType){
        List<GPathResult> filteredList = root.children().findAll{
            XMLSlurperUtil.name(it as GPathResult) == fieldType
        } as List<GPathResult>
        List<ImField> fields = []
        filteredList.each{GPathResult it,  int index ->
            fields.add(Class.forName(fieldClass).newInstance() as ImField)
            fields[index].set(it)
        }
        fields
}

函数调用如下所示:

ImStageUtil.getFields(root, ImFieldFactory.SOURCE_FIELD, ImParserConstants.SOURCE_FIELD)

在哪里ImFieldFactory.SOURCE_FIELD = "com.dto.fields.SourceField"ImParserContants.SOURCE_FIELD = "SOURCEFIELD"

错误发生在.each关闭行:

No signature of method: com.extractor.ImStageUtil$_getFields_closure11.doCall() is applicable for argument types: (groovy.util.slurpersupport.NodeChild) values: []
Possible solutions: doCall(groovy.util.slurpersupport.GPathResult, int), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object)
groovy.lang.MissingMethodException: No signature of method: com.extractor.ImStageUtil$_getFields_closure11.doCall() is applicable for argument types: (groovy.util.slurpersupport.NodeChild) values: []
Possible solutions: doCall(groovy.util.slurpersupport.GPathResult, int), findAll(), findAll(), isCase(java.lang.Object), isCase(java.lang.Object)
4

1 回答 1

0

我试图创建一个与您的示例类似的脚本,有两件事我必须修改(如果您filteredList的不是空的,您需要先检查):

1-您需要collect()findAll{}关闭后使用,这允许您收集所有条目并将它们添加到您的filteredList.

2-您正在使用.each{}并且您正在提供一个List索引,这应该被替换,.eachWithIndex{}因为第一个不期望索引。这是您的代码的简化版本:

import groovy.util.slurpersupport.GPathResult

def text = '''
    <list>
        <technology>
            <name>Groovy</name>
        </technology>
    </list>
'''

def list = new XmlSlurper().parseText(text)

def List getFields(GPathResult root,String fieldClass, String fieldType){
        List<GPathResult> filteredList = root.children().findAll{
            //println(it)
            it != null
        }.collect() as List<GPathResult>

        println('list: ' + filteredList.getClass() + ', ' + filteredList.size())

        filteredList.eachWithIndex{GPathResult it,  int index ->
            println('it: ' + it)
        }
}

getFields(list, '', '')

最后一个例子对我来说没有任何例外。

希望这可以帮助。

于 2020-04-04T16:14:33.150 回答