Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

Load script from groovy script

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.

question from:https://stackoverflow.com/questions/9004303/load-script-from-groovy-script

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...