Using Jenkins Shared Libraries as classes

徘徊边缘 提交于 2019-12-10 18:06:12

问题


I have a Jenkins file, and i'm trying to instantiate a groovy class from my shared library. I get "unable to resolve class Test "

I have a src/com/org/foo.groovy file in a shared library :

package com.org

class Test implements Serializable{
  String val
  Test(val) {
    this.val = val
  }
}

and I'm trying to instantiate it in my jenkinsfile

@Library('Shared-Library@master') 
import com.org //also tried to use with .foo with no success

def t = new Test("a") //doesnt work
def t = new foo.Test("a")//doesnt work
def t = new com.org.foo.Test("a")//doesnt work

What does work is if I refer to the file as a class (which I don't have the access to its constructor). That is:

@Library('Shared-Library@master')
def t = new foo.com.org.foo()

This is nice, and lets me use foo functions. However, I lose the power to give the class constants and construct it with parameters.

Any idea how I can define and use a class from shared library? Thanks


回答1:


  1. The scope of your class is a default scope. you can change the scope to public
  2. It throwing an error because you have created an object of a class outside the script block. try below code and it should work. Try below code
@Library('Shared-Library@master') 
import com.org.*;

stages{
   stage('Demo') {  
      steps{
         script{
            def t = new Test("a") //this should work
         }
      }
   }
}  


来源:https://stackoverflow.com/questions/50005082/using-jenkins-shared-libraries-as-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!