3

I'm a groovy novice, so not sure if this is possible. I need something like an import, but not quite. Here is the simplified code example of what I'm trying to do:

in file FileToProcess.groovy I have

class FileToProcess implements Serializable {
  String FileName

  FileToProcess(fileName) {
   this.FileName = fileName;
  }
}

and then in a JenkinsFile I want to do something like

F1 = new FileToProcess('A');
List<FileToProcess> allFiles = new ArrayList<FileToProcess>();
allFiles.add(F1);
​for (FileToProcess file : allFiles) {
    System.out.println(file.FileName);
}

Now, on StackOverflow I've found examples of how to instantiate a class from another file, for example here or here, and that solves the line

F1 = new FileToProcess('A');

but it does not show how to use that class as a type in a declaration, for example

List<FileToProcess> allFiles = new ArrayList<FileToProcess>();

gives me "unable to resolve class FileToProcess". I also know that using a class as a type like this should work, because it does when I put the class in the same JenkinsFile, so the problem seems to be just that the class is not visible in the JenkinsFile.

Is there a way to do this?

NP3
  • 1,114
  • 1
  • 8
  • 15

1 Answers1

0

I'm not sure how you tried to setup your class libraries but I attempted the same while using a class from a pipeline shared library and it worked as intended https://jenkins.io/doc/book/pipeline/shared-libraries/

I did do it a little differently: assuming you places the file under src/org/Foo.groovy

import org.Foo

def list = new ArrayList<Foo>
list.add(new Foo('str1'))
list.add(new Foo('str2'))
Kelrak
  • 28
  • 4
  • Well, I just have the groovy file next to the JenkinsFile, in the same folder, and they are pulled from git by Jenkins. I didn't use the shared libraries. Is that the only way to do this? I can't just use load or import it directly from the file? – NP3 Oct 10 '17 at 12:03
  • I've only used the pipeline libraries option so far personally. Regardless I also think it's a bit better to manage that code that way – Kelrak Oct 10 '17 at 14:00