java - 使用正确的参数在 groovy 脚本之间调用方法

标签 java grails groovy soapui

我刚开始学习 groovy 并尝试将我的 java 代码转换为 groovy 脚本。通常java允许你有一个类只有你可以从其他类调用的方法。我想把它翻译成 groovy。我有一个文件 - 让我们称之为 File1 - 一种像这样的方法:

def retrieveData(String name){  
// do something
}

在第二个文件 File2 中,我这样调用 File1:

def file1Class = this.class.classLoader.parseClass(new File("../File1.groovy"))

然后尝试像这样调用 File1 中的方法:

def data = file1Class.retrieveData("String")

但它一直给我这个错误 - MissingMethodException:

groovy.lang.MissingMethodException: No signature of method: static File1.retrieveData() is applicable for argument types: (java.lang.String) values: [String] Possible solutions: retrieveData(java.lang.String)

所以它确实识别出我发送了正确数量的参数甚至正确的对象,但它没有按预期运行该方法? 有什么我想念的吗?我试图从方法中删除对象定义——换句话说——像这样:

def retrieveData(name){  
// do something
}

但这也没有用。我对下一步是什么一无所知。谁能帮助我朝着正确的方向前进?我将不胜感激。

最佳答案

请参阅 this StackOverflow reponse 中提供的答案.

使用GroovyScriptEngine class . GroovyScriptEngine 有什么作用?来自文档:

Specific script engine able to reload modified scripts as well as dealing properly with dependent scripts.

请参阅下面的示例。

def script = new GroovyScriptEngine( '.' ).with {
  loadScriptByName( '..\File1.groovy' )
} 
this.metaClass.mixin script

retrieveData()

注意我们如何使用loadScriptByName方法来

Get the class of the scriptName in question, so that you can instantiate Groovy objects with caching and reloading.

这将允许您随心所欲地从文件访问 Groovy 对象。

关于java - 使用正确的参数在 groovy 脚本之间调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42163504/

相关文章:

if-statement - 有条件的 Jenkins 管道作业

java.lang.NoClassDefFoundError : com/android/utils/ILogger into visual studio 2015 错误

java - 速度模板 - 换行

grails - 值与变量相同的Grails复选框

groovy - 在 Groovy 控制台中使用 Geb

json - 用于验证键是否存在的 SoapUI 脚本断言,而不验证键中的值

java - 在 Liberty 中创建 EJB 计时器

java - 将 java.long 映射到 oracle.Number(14)

sql - 在 Grails SQL 查询结果中包含列名

grails - 域约束不起作用