JenkinsFile groovy中的闭包-回调或委托

pog*_*man 3 groovy closures jenkins jenkins-pipeline

我希望能够在Jenkins Groovy脚本中添加回调作为参数。我认为关闭是我所需要的,但我不知道该怎么做。这是我想要的输出:

enter
hello
exit
Run Code Online (Sandbox Code Playgroud)

Jenkins文件:

def rootDir = pwd()
def tools = load "${rootDir}\\patchBuildTools.groovy"
mainMethod(tools.testCl("hello"))
Run Code Online (Sandbox Code Playgroud)

patchBuildTools.groovy

def mainMethod(Closure test) {
    println "enter"
    test()
    println "exit"
}


def testCl(String message) {
    println message
}
Run Code Online (Sandbox Code Playgroud)

这给了我输出:

hello
enter
java.lang.NullPointerException: Cannot invoke method call() on null object
Run Code Online (Sandbox Code Playgroud)

是否可以获取我想要的电话订单?

更新-根据答案

Jenkins文件:

def rootDir = pwd()
def tools = load "${rootDir}\\patchBuildTools.groovy"
mainMethod("enter", "exit")
{
  this.testCl("hello")
}
Run Code Online (Sandbox Code Playgroud)

patchBuildTools.groovy

def mainMethod(String msg1, String ms2, Closure test) {
  println msg1
  test()
  println ms2
}



def testCl(String message) {
    println message
}
Run Code Online (Sandbox Code Playgroud)

tft*_*ftd 6

您可能误解了闭包的工作原理-闭包是一个匿名函数,您可以将其传递给另一个函数并执行。

话虽如此,在你的榜样,你是路过的结果testCl(),这是一个String,来mainMethod()。这是错误的,因为mainMethod期望a Closure而不是a String作为传递的参数。

我不确定您要达到的目标,但是可以使用以下方法Closure

詹金斯档案

def rootDir = pwd()
def tools = load "${rootDir}\\patchBuildTools.groovy"
mainMethod() {
    echo "hello world from Closure"
}    
Run Code Online (Sandbox Code Playgroud)

patchBuildTools.groovy

def mainMethod(Closure body) {
    println "enter"
    body() // this executes the closure, which you passed when you called `mainMethod() { ... }` in the scripted pipeline
    println "exit"
}
Run Code Online (Sandbox Code Playgroud)

结果

enter
hello world from Closure
exit
Run Code Online (Sandbox Code Playgroud)