【问题标题】:Parsing classes with GroovyShell使用 GroovyShell 解析类
【发布时间】:2014-07-28 05:52:54
【问题描述】:

我有一个 groovy 脚本,它需要在外部 groovy 脚本内的类中运行一个方法。 我知道如何在外部 groovy 脚本中运行方法:

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

但是如果方法在一个类中呢?我试过这个,但它给了我一个错误。

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

【问题讨论】:

  • 你能发一个样本foo.groovy吗?反正theclass好像需要实例化
  • theclass.newInstance().method()

标签: groovy groovyshell


【解决方案1】:

您可以使用 Java 反射来创建位于另一个脚本中的 Class 的新实例:

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

您的外部文件中的脚本是这样的:

class ClassInAnotherObject{
    def doSth(){
    }
}

但脚本文件中可能有更多的类,也可能有更多的指令和方法调用。就像普通的 groovy 脚本一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多