如何修复groovy.lang.MissingMethodException:没有方法的签名:

ger*_*etd 20 groovy

我试图在没有闭包的情况下使用此方法

def copyAndReplaceText(source, dest, targetText, replaceText){
    dest.write(source.text.replaceAll(targetText, replaceText))
}

def source = new File('C:/geretd/resumebak.txt') //Hello World
def dest = new File('C:/geretd/resume.txt') //blank

copyAndReplaceText(source, dest){
    it.replaceAll('Visa', 'Passport!!!!')
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行它时,我收到以下错误:

groovy.lang.MissingMethodException: No signature of method: ConsoleScript3.copyAndReplaceText() is applicable for argument types: (java.io.File, java.io.File, ConsoleScript3$_run_closure1) values: [C:\geretd\resumebak.txt, C:\geretd\resume.txt, ...]
Possible solutions: copyAndReplaceText(java.lang.Object, java.lang.Object, java.lang.Object, java.lang.Object)

at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)

at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:78)

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:149)
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Wil*_*ill 16

因为您将三个参数传递给四个参数方法.此外,您没有使用传递的闭包.

如果要指定在source内容之上进行的操作,请使用闭包.它会是这样的:

def copyAndReplaceText(source, dest, closure){
    dest.write(closure( source.text ))
}

// And you can keep your usage as:
copyAndReplaceText(source, dest){
    it.replaceAll('Visa', 'Passport!!!!')
}
Run Code Online (Sandbox Code Playgroud)

如果您将始终交换字符串,则传递两者,因为您的方法签名已经指出:

def copyAndReplaceText(source, dest, targetText, replaceText){
    dest.write(source.text.replaceAll(targetText, replaceText))
}

copyAndReplaceText(source, dest, 'Visa', 'Passport!!!!')
Run Code Online (Sandbox Code Playgroud)

  • 我希望你喜欢groovy.我觉得与之合作很愉快:-) (2认同)

рüф*_*ффп 10

就我而言,这只是我有一个与函数名称相同的变量。

例子:

def cleanCache = functionReturningABoolean()

if( cleanCache ){
    echo "Clean cache option is true, do not uninstall previous features / urls"
    uninstallCmd = ""
    
    // and we call the cleanCache method
    cleanCache(userId, serverName)
}
...
Run Code Online (Sandbox Code Playgroud)

后来在我的代码中我有这个功能:

def cleanCache(user, server){

 //some operations to the server

}
Run Code Online (Sandbox Code Playgroud)

显然 Groovy 语言不支持这一点(但其他语言如 Java 则支持)。我刚刚将我的函数重命名为executeCleanCache,它运行得很好(或者您也可以将变量重命名为您喜欢的任何选项)。


Gly*_*ine 8

帮助其他漏洞猎人。我有这个错误,因为该函数不存在。

我有一个拼写错误。

  • 感谢您为我指明了正确的方向。我的方法名称大小写不同。哎呀! (2认同)