4

I have a file that contains classes. Example :


abstract class TestBase
{
    String name
    abstract def fTest()

    def bobby(){
        return "bobby"
    }
}
class Test extends TestBase
{
    def fTest(){
        return "hello"
    }
}
class Test2 extends TestBase
{
    def fTest(){
        return "allo"
    }
    def func(){
        return "test :)"
    }
}

I want to import the file in my Jenkins pipeline script, so I can create an object of one of my class. For example :


def vTest = new Test()
echo vTest.fTest()
def vTest2 = new Test2()
echo vTest2.func()

How can I import my file in my Jenkins Pipeline ? Thx.

Emile
  • 592
  • 10
  • 36

1 Answers1

5

you can do like this:

Classes.groovy

class A{
    def greet(name){ return "greet from A: $name!" }
}

class B{
    def greet(name){ return "greet from B: $name!" }
}

// this method just to have nice access to create class by name
Object getProperty(String name){
    return this.getClass().getClassLoader().loadClass(name).newInstance();
} 

return this

pipeline:

node{
    def cl = load 'Classes.groovy'
    def a = cl.A
    echo a.greet("world A")
    def b = cl.B
    echo b.greet("world B")
}
daggett
  • 26,404
  • 3
  • 40
  • 56
  • 1
    It gives me the error : groovy.lang.MissingPropertyException: No such property: A for class... – Emile Aug 14 '17 at 20:51
  • try `def a = cl.getProperty('A')` instead of `def a = cl.A` – daggett Aug 15 '17 at 10:44
  • that's a question to your jenkins administrator. – daggett Jul 15 '20 at 17:01
  • Scripts not permitted to use method java.lang.Class getClassLoader. Administrators can decide whether to approve or reject this signature. - how solve this problem? – Nikolay Baranenko Apr 15 '21 at 09:42
  • https://stackoverflow.com/questions/38276341/jenkins-ci-pipeline-scripts-not-permitted-to-use-method-groovy-lang-groovyobject – daggett Apr 15 '21 at 11:10
  • I get the same error as @Emile. I feel like there's got to be a way to access the class from loaded groovy without jumping through hoops. Accessing functions from loaded groovy is easy and works as expected. – Aaron Wright Aug 03 '21 at 14:16