从groovy脚本加载脚本

pto*_*oos 36 groovy load

File1.groovy

def method() {
   println "test"
}
Run Code Online (Sandbox Code Playgroud)

File2.groovy

method()
Run Code Online (Sandbox Code Playgroud)

我想在运行时加载/包含File1.groovy中的函数/方法,等于rubys/rake的加载.它们位于两个不同的目录中.

tim*_*tes 29

如果你不介意file2中的代码在一个with块中,你可以这样做:

new GroovyShell().parse( new File( 'file1.groovy' ) ).with {
  method()
}
Run Code Online (Sandbox Code Playgroud)

另一种可能的方法是file1.groovy改为:

class File1 {
  def method() {
    println "test"
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在file2.groovy你可以mixin用来添加方法file1

def script = new GroovyScriptEngine( '.' ).with {
  loadScriptByName( 'file1.groovy' )
} 
this.metaClass.mixin script

method()
Run Code Online (Sandbox Code Playgroud)


Art*_*ero 16

您可以使用GroovyShell评估Groovy中的任何表达式或脚本.

File2.groovy

GroovyShell shell = new GroovyShell()
def script = shell.parse(new File('/path/file1.groovy'))
script.method()
Run Code Online (Sandbox Code Playgroud)


clm*_*art 13

如果file1.groovy是实际的课程,这将是最简单的class File1 {...}.

鉴于此,另一种方法是将文件加载到GroovyClassLoader:

this.class.classLoader.parseClass("src/File1.groovy")

File1.method() 

File1.newInstance().anotherMethod()
Run Code Online (Sandbox Code Playgroud)

  • 你也可以说def script = this.class.classLoader.parseClass("..."); def object = script.newInstance() (2认同)

OK9*_*999 9

我迟到了但是.这就是我们如何实现您的要求.所以,我有一个像这样的file1.gsh:

文件1:

println("this is a test script")

def Sometask(param1, param2, param3)
{
    retry(3){
        try{
            ///some code that uses the param
        }
        catch (error){
            println("Exception throw, will retry...")
            sleep 30
            errorHandler.call(error)
        }
    }
}

return this;
Run Code Online (Sandbox Code Playgroud)

在另一个文件中,可以通过首先实例化来访问这些函数.所以在file2中.

文件2:

def somename
somename = load 'path/to/file1.groovy'
 //the you can call the function in file1 as

somename.Sometask(param1, param2, param3)
Run Code Online (Sandbox Code Playgroud)

  • 完美地在Jenkins管道上工作!(注意:首先,我忘记了在脚本末尾的`return this`,所以`load`返回`null`). (4认同)
  • 'load'仅在jenkins上下文中运行时才有意义.它不是时髦语言的一部分. (4认同)
  • 如上面的@Hoobajoob所述,这是Jenkins管道DSL,而不是Groovy语言功能。 (2认同)

小智 5

这是我正在使用的。

any_path_to_the_script.groovy1:以班级形式编写

2:在调用脚本中,使用:

def myClass = this.class.classLoader.parseClass(new File("any_path_to_the_script.groovy"))
myClass.staticMethod()
Run Code Online (Sandbox Code Playgroud)

它在 Jenkins Groovy 脚本控制台中运行。我没有尝试过非静态方法。

  • (与上面类似答案的评论相同)我也一直在使用这个(在詹金斯),看起来这正在吞噬 PermSpace。请参阅此处:http://stackoverflow.com/questions/24169976/understanding-groovy-grails-classloader-leak http://stackoverflow.com/questions/712187/troubleshooting-grails-groovy-memory-leaks 因此我想知道这是否确实应该推荐用于服务器应用程序。 (2认同)