简体   繁体   English

在Jenkins管道脚本中将另一个groovy文件中的类用作类型

[英]Using class from another groovy file as a type in a Jenkins pipeline script

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 在文件FileToProcess.groovy中

class FileToProcess implements Serializable {
  String FileName

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

and then in a JenkinsFile I want to do something like 然后在JenkinsFile中我想做类似的事情

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 现在,在StackOverflow上,我找到了有关如何从另一个文件实例化类的示例,例如herehere ,并且可以解决以下问题:

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". 给我“无法解析类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. 我也知道使用类作为这样的类型应该可以工作,因为当我将类放入相同的JenkinsFile时确实可以,所以问题似乎只是该类在JenkinsFile中不可见。

Is there a way to do this? 有没有办法做到这一点?

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/ 我不确定您是如何尝试设置类库的,但是在使用管道共享库中的类时我尝试了相同的方法,并且它按预期工作了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 我的做法有所不同:假设您将文件放在src/org/Foo.groovy

import org.Foo

def list = new ArrayList<Foo>
list.add(new Foo('str1'))
list.add(new Foo('str2'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM