【问题标题】:Adding a method from an external groovy script with GroovyShell()使用 GroovyShell() 从外部 groovy 脚本添加方法
【发布时间】:2014-07-26 21:21:18
【问题描述】:

我有一个 groovy 脚本 (source.groovy),它需要从另一个 groovy 脚本 (external.groovy) 调用一个方法。问题是 external.groovy 导入了一个不存在的库,因此出现错误。这是一个例子:

Source.groovy:

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

这里是 external.groovy:

import com.foo.doesnotexsist
def method() {println "test"}

当我运行 Source.groovy 时出现错误,因为 com.foo.doesnotexsist 不存在。我不在乎它不存在,因为它不会影响 method() 函数。有什么方法可以调用 method() 函数吗?

【问题讨论】:

  • Groovy 的版本是多少?
  • 您可以从文件中删除该行吗?

标签: groovy groovyshell


【解决方案1】:

也许这不是我们想要实现的方式,但有一个简单的解决方案可以删除不需要的导入:

def text = new File( 'external.groovy' ).findAll{!(it =~ /^\s*import/)}.join('\n')
new GroovyShell().parse( text ).with{method()}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多