Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Groovy使方法从一个脚本到另一个脚本可见_Java_Groovy - Fatal编程技术网

Java Groovy使方法从一个脚本到另一个脚本可见

Java Groovy使方法从一个脚本到另一个脚本可见,java,groovy,Java,Groovy,我有一个脚本,其中包含我想从其他脚本访问的实用程序方法 我在java代码中这样加载脚本 static { GroovyShell shell = new GroovyShell(); //This is the script that has the utility groovyUtils = shell.parse(new InputStreamReader(MyJavaClass.class.getResourceAsStream("scripts/json/MyU

我有一个脚本,其中包含我想从其他脚本访问的实用程序方法

我在java代码中这样加载脚本

static {
    GroovyShell shell = new GroovyShell();
    //This is the script that has the utility 
    groovyUtils = shell.parse(new InputStreamReader(MyJavaClass.class.getResourceAsStream("scripts/json/MyUtils.groovy")));
    //This is the script that does thing
    groovyScript = shell.parse(new InputStreamReader(MyJavaClass.class.getResourceAsStream("scripts/json/MyScript.groovy")));
}

我想公开
MyUtils.groovy
中的方法,以便在
MyScript.groovy
(以及将来的其他脚本)

实现这一点的方法有很多

你说的是方法,所以我猜你在
MyUtils.groovy
中有一个类。 在这种情况下,您可以指定
绑定
,例如

def myUtils = new MyUtils()
def binding= new Binding([  method1: myUtils.&method1  ]) 
def shell= new GroovyShell(binding)

shell.evaluate(new File("scripts/json/MyScript.groovy"))
在上面的代码中,您可以在脚本中引用
method1
,最终将在
myUtils
实例上调用它

另一种解决方案是指定脚本基类,例如

def configuration = new CompilerConfiguration()
configuration.setScriptBaseClass('MyUtils.groovy')
def shell = new GroovyShell(this.class.classLoader, new Binding(), configuration)
MyUtils
类必须扩展
Script
然后;它的所有方法都可以在使用
shell
解析的脚本中使用



实际上,有多种方法可以嵌入/运行Groovy。在设计DSL时经常讨论这些问题。例如,如果您以前没有搜索过,您可以查看一下。

这也是我在Google/Stackoverflow上搜索时收集到的信息,但它并不真正适用于我,因为1。我的脚本在类路径和2中。我正在用Java而不是groovy创建GroovyShell。我现在的一个临时解决方案是从脚本加载文本,然后执行
Script myScript=shell.parse(textFromUtils+System.lineSeparator()+textFromMyScript)@NicolasMartel我的脚本在类路径中-这应该没有效果,只是使用不同的输入方法。我正在用Java创建我的GroovyShell——这同样应该没有什么区别;只需删除我使用的所有语法。在Java中如何
创建新绑定([method1:myUtils.&method1])
?我对Groovy还是有点陌生,所以我不完全确定这会翻译成什么into@NicolasMartel
[key:value]
只是一个映射文字,请阅读更多。因此,在Java中,只需传递一个
HashMap
(默认情况下,
[k:v]
就是这样实现的)
myUtils.&method1
是一个方法引用,所以要么构建一个匿名的
闭包
要么。。。在Java8中传递方法引用。不过还有其他方法(我只给了你2种),所以选择你觉得最好的。