Pipeline shared libraries, can I have a constructor when I don't explicitly declare the enclosing class?

26 views
Skip to first unread message

Jonathan Hodgson

unread,
Nov 7, 2016, 4:54:56 PM11/7/16
to Jenkins Users
Hi,

I'm setting up a folder library as per here.

Now in one of their examples they talk about not declaring the enclosing class (so as to allow access to steps)

This works fine, in the file MyClass.groovy

@package my.package



def myMethod(data)
{
   
// do stuff with data
}


return this


I can declare an instance of the class and use it with 

method = new my.package.MyClass()


myClass
.myMethod(my_data)


But I cannot create a contructor, is there a way to do this?

thomas....@teamaol.com

unread,
Nov 8, 2016, 7:57:39 AM11/8/16
to Jenkins Users
When you define a class then you can write a function that returns an instance of that class.
Just the way you write it ... you do not write a class ... you get an instance of the library which contains functions

class Foo {
   
def sum(a, b) {
       
return a + b
   
}
}

def createFoo() {
   
return new Foo()
}

def sum(a, b){
   
return a + b
}

return this;

Assume the file is foo.groovy you can do then:

def fooApi = load pwd() + '/foo.groovy'
echo "10+20=" + fooApi.sum(10, 20).toString()
def foo = fooApi.createFoo()
echo
"10+20=" + foo.sum(10, 20).toString()

kind of ...
I hope this helps ...
Reply all
Reply to author
Forward
0 new messages