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)
我迟到了但是.这就是我们如何实现您的要求.所以,我有一个像这样的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)
小智 5
这是我正在使用的。
any_path_to_the_script.groovy
1:以班级形式编写
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 脚本控制台中运行。我没有尝试过非静态方法。