gpt4 book ai didi

java - 如何从 Java 调用 groovy 类的方法 - 字符串格式的方法名称和参数

转载 作者:行者123 更新时间:2023-11-30 08:36:39 24 4
gpt4 key购买 nike

我有一个 Java 程序,它接受以下格式的一些字符串输入:

setData("hello")

此外,我还有一个 groovy 脚本“sample.groovy”,它是一个具有以下示例格式的 groovy 文件:

class sample
{
def doOperation()
{
println("Inside doOperation()")
}

def setData(String str)
{
println("Incoming data : " + str)
}
}

从 Java 类中,创建一个名为 sampleObj 的上述 groovy 类的对象。

我必须使用输入字符串 say "setData("hello")"从我的 Java 应用程序调用 sampleObj.setData("hello")

那我怎么调用这个方法呢?

最佳答案

这正是 GroovyShell 遇到的问题解决。

这是一个例子:

import groovy.transform.Canonical
import org.codehaus.groovy.control.CompilerConfiguration

@Canonical
class ScriptState {
String data
}

abstract class MyScript extends Script {
void setData(String data) {
binding.state.data = data
}
}

def state = new ScriptState()
def cc = new CompilerConfiguration(scriptBaseClass: MyScript.class.name)

def shell = new GroovyShell(MyScript.classLoader, new Binding(state: state), cc)

shell.evaluate('println "Running script"; setData "The Data"')

assert state.data == 'The Data'

println state

运行它会打印:

Running script
ScriptState(The Data)

我将此示例基于 Groovy Goodness示例。

通常,您不需要像我在 MyScript.classLoader 中那样设置类加载器...我只需要这样做,因为我将其作为脚本运行,脚本类将如果我不这样做,GroovyShell 的脚本类加载器将看不到它。

编辑

问题经过大量编辑后,问题似乎是您不知道从脚本调用的 Java 对象将具有哪个类

在那种情况下,只需将 MyScript 类更改为执行如下操作:

abstract class MyScript extends Script {
def methodMissing(String name, args) {
// this will call any method called inside the script
// on the sample Object
binding.sampleObject."$name"(*args)
}
}

现在,在创建 GroovyShell 时:

def shell = new GroovyShell(
MyScript.classLoader,
new Binding(sampleObject: new Sample()),
cc)

运行这段代码:

shell.evaluate('doOperation(); setData "The Data"')

将打印预期的:

Inside doOperation()
Incoming data : The Data

关于java - 如何从 Java 调用 groovy 类的方法 - 字符串格式的方法名称和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37607706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com