Load script from groovy script
Solution 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()
Solution 2:
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()
Solution 3:
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()