6

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

mkobit
  • 43,979
  • 12
  • 156
  • 150
balaganAtomi
  • 550
  • 8
  • 13
  • 3
    Why define it in `foo.groovy` instead of naming it `Test.groovy`? I don't know if there is weirdness with Groovy or weirdness with Jenkins Groovy that makes the compilation behave oddly. If you do `import com.org.foo` and `println(foo)` it would print out `class com.org.Test`. – mkobit Apr 24 '18 at 16:39
  • 2
    this is a javaism: keep class name == file name. – mvk_il Aug 05 '18 at 14:54

1 Answers1

0
  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
         }
      }
   }
}  
papanito
  • 2,349
  • 2
  • 32
  • 60