Parsing classes with GroovyShell

*爱你&永不变心* 提交于 2019-12-13 03:52:09

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/24090660/parsing-classes-with-groovyshell

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