一、报错信息
在使用 Groovy 闭包时 , 会报如下错误 :
代码语言:javascript复制Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: Test$_main_closure3.call() is applicable for argument types: (java.lang.String) values: [Hello]
Possible solutions: doCall(), any(), any(), each(groovy.lang.Closure), any(groovy.lang.Closure), each(groovy.lang.Closure)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:284)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1015)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:806)
at groovy.lang.GroovyObjectSupport.invokeMethod(GroovyObjectSupport.java:44)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:45)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at Test.main(Test.groovy:50)
Execution failed for task ':Test.main()'.
> Process 'command 'D:/Program Files/Java/jdk1.8.0_221/bin/java.exe'' finished with non-zero exit value 1
二、解决方案
上述类型的错误 , 是由于闭包中传入参数错误导致的 ;
代码语言:javascript复制Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: Test$_main_closure3.call() is applicable for argument types: (java.lang.String) values: [Hello]
Possible solutions: doCall(), any(), any(), each(groovy.lang.Closure), any(groovy.lang.Closure), each(groovy.lang.Closure)
原代码 : 其中闭包中有 " -> " 符号 , 表示闭包不希望接收任何参数 ;
代码语言:javascript复制 def closure2 = { ->
println "Hello"
}
closure2("Hello")
修改后代码 : 删除闭包中的参数 , 即可正确执行该闭包 ;
代码语言:javascript复制 def closure2 = { ->
println "Hello"
}
closure2()