【问题标题】:Groovy : Class.forName().newInstance() errorGroovy:Class.forName().newInstance() 错误
【发布时间】:2020-07-15 15:54:19
【问题描述】:

我有以下方法,其中我使用List<GPathResult> filteredList 返回一个List<ImField> 对象。我在我生成的地方执行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)

【问题讨论】:

    标签: oop groovy reflection closures gpath


    【解决方案1】:

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

    1- 您需要在findAll{} 闭包之后使用collect(),这允许您收集所有条目并将它们添加到您的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, '', '')
    

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

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-25
      • 2017-12-26
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多