Load script from groovy script

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

File1.groovy

def method() {    println "test" }

File2.groovy

method()

I want to load/include the functions/methods from File1.groovy during runtime, equals to rubys/rake's load. They are in two different directories.

回答1:

If you don't mind the code in file2 being in a with block, you can do:

new GroovyShell().parse( new File( 'file1.groovy' ) ).with {   method() }

Another possible method would be to change file1.groovy to:

class File1 {   def method() {     println "test"   } }

And then in file2.groovy you can use mixin to add the methods from file1

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


回答2:

It will be easiest if file1.groovy is an actual class class File1 {...}.

Given that, another way to do it is to load the file into the GroovyClassLoader:

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


回答3:

You can evaluate any expression or script in Groovy using the GroovyShell.

File2.groovy

GroovyShell shell = new GroovyShell() def script = shell.parse(new File('/path/file1.groovy')) script.method()


回答4:

I am late on this but. This is how we have been achieving what you were asking. So, i have a file1.gsh like so:

File1:

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;

And in the other file, these functions can be accessed by instantiating first. So in file2.

File2:

def somename somename = load 'path/to/file1.groovy'  //the you can call the function in file1 as  somename.Sometask(param1, param2, param3)


回答5:

Here is what I'm using.

1: Write any_path_to_the_script.groovy as a class

2: In the calling script, use:

def myClass = this.class.classLoader.parseClass(new File("any_path_to_the_script.groovy")) myClass.staticMethod()

It's working in the Jenkins Groovy script console. I have not tried non-static methods.



转载请标明出处:Load script from groovy script
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!