Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load script from groovy script

Tags:

groovy

load

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.

like image 262
ptomasroos Avatar asked Jan 25 '12 14:01

ptomasroos


People also ask

How do I run a Groovy script in Java?

With the GroovyClassLoader we can load Groovy scripts and run them in Java code. First we must create a new GroovyClassLoader and then parse a Groovy script. The script can be in a file, string or inputstream. Once the script is parsed we have a Class and we can make a new instance of this class.

How you can include a Groovy script in another Groovy?

For example, using "some/subpackage/Util. groovy" would result in searching at WORK_DIR/some/subpackage/Util. groovy . Follow the Java class naming convention to name your groovy scripts.


1 Answers

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() 
like image 75
tim_yates Avatar answered Sep 28 '22 08:09

tim_yates