0

I have a groovy script that need to run a method inside a class inside an external groovy script. I know how to run a method within an external groovy script:

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

But what if the method is inside a class? I tried this but it gave me an error.

new GroovyShell().parse( new File( 'foo.groovy' ) ).with {
    theclass.method()
  }
user2475310
  • 733
  • 4
  • 13
  • 19

1 Answers1

0

You can use Java reflection to create new instance of a Class that is located in another script:

File sourceFile = new File("D:\\anoutherScript.groovy")
//here you have to update your classloader with external script
getClass().getClassLoader().addURL(sourceFile.toURI().toURL())
GroovyObject obj = Class.forName("ClassInAnotherObject").newInstance()
obj.doSth()

Script in your external file would be like that:

class ClassInAnotherObject{
    def doSth(){
    }
}

but there could be more classes in script file, also some more instructions and method call. Just like normal groovy script.

hexin
  • 947
  • 7
  • 17