有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我刚刚开始学习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
}

但这也不管用。我不知道下一步会是什么。谁能帮我向正确的方向走?我将不胜感激


共 (1) 个答案

  1. # 1 楼答案

    参见this StackOverflow reponse中提供的答案

    使用GroovyScriptEngineclass。这个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对象