k_vishwanath
k_vishwanath

Reputation: 1585

Use of this keyword as an argument to the class constructor in Jenkins file

I recently came across the following lines in Jenkinsfile

def obj = new Foo(this, params)
obj.someMethod()

what is the use of this keyword as an argument to the class constructor?

Upvotes: 5

Views: 2167

Answers (1)

k_vishwanath
k_vishwanath

Reputation: 1585

this keyword is used to pass pipeline steps to a library class, in a constructor, or just one method

Suppose I have the following pipeline

pipeline{
  agent any
  stages {
    stage {
      steps {
        echo "Inside Steps block"
        script {
           echo "Hello World"
           sh 'date'
           def obj = new Bar(this)
           obj.test()
        }
      }
    }
  }
}

And this is how the class file looks

class Bar implements Serializable {
  def steps
  Bar(steps) {
    this.steps = steps
  }

  void test() {
    this.steps.echo 'Hello World inside class Method'
    this.steps.sh 'date'
  }
}

So basically whatever steps you can execute inside pipeline can be used inside the groovy class by passing this keyword to the class constructor

More info can be found from the official doc

Upvotes: 1

Related Questions