用GroovyShell解析类 [英] Parsing classes with GroovyShell
本文介绍了用GroovyShell解析类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Groovy脚本,需要在外部groovy脚本中的类中运行方法. 我知道如何在外部Groovy脚本中运行方法:
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()
}
推荐答案
您可以使用Java反射来创建位于另一个脚本中的Class的新实例:
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.
这篇关于用GroovyShell解析类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文