How to import a class from a Jenkins Shared Library into the pipeline

cauchy picture cauchy · May 23, 2018 · Viewed 7.8k times · Source

I was using some global methods in the /var directory of the shared library, and everything worked fine. Now I need to keep the state of the process, so I'm writting a groovy class. Basically I have a class called 'ClassTest.groovy' in '/src' which is something like this;

class ClassTest {
    String testString
    def method1() { ... }
    def method2() { ... }
}

and at the begining of the pipeline

library 'testlibrary@'
import ClassTest

with result:

WorkflowScript: 2: unable to resolve class ClassTest @line 2, column 1.
import ClassTest

before, I was just goind

library 'testlibrary@' _

and using the methods as

script {
    libraryTest.method1()
    ...
    libraryTest.method2()
}

where the methods were in a file '/var/libraryTest.groovy' and everything worked. So I know that the shared library is there, but I'm confused with the way groovy / Jenkins handle classes / shared libraries.

What's the correct way to import a class? I cannot find a simple example (with groovy file, file structure and pipeline) in the documentation.

EDIT: I moved the file to 'src/com/company/ClassTest.groovy' and modified the pipeline as

@Library('testlibrary@') import com.company.ClassTest
def notification = new ClassTest()

but now the error is

unexpected token: package @ line 2

the first two lines of the groovy file are:

// src/com/company/ClassTest.groovy
package com.company;

Answer

cauchy picture cauchy · May 24, 2018

So far this is what I've found.

To load the library in the pipeline I used:

@Library('testlibrary@') import com.company.ClassTest
def notification = new ClassTest()

In the class file, no package instruction. I guess that I don't need one because I don't have any other files or classes, so I don't really need a package. Also, I got an error when using the same name for the class and for the file where the class is. The error specifically complained and asked for one of them to be changed. I guess this two things are related to Jenkins.

That works, and the library is loaded.