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/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(以及 future 的其他脚本)中使用

最佳答案

您可以通过多种方式实现这一目标。

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

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 时经常被讨论。你可以看看例如here ,如果您之前没有搜索过它。

关于java - Groovy 使方法从一个脚本到另一个脚本可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22234166/

相关文章:

java - 获取用 Java 或 Groovy 填充的有效 oauth_signature 的绝对最小代码?

android - Gradle 动态 flavor

java - setOpaque() 方法

java - 双向链表实现

java - RecyclerView 没有 LayoutManager android.support.v7.widget.RecyclerView

grails - BootStrap.groovy 中的访问 Controller 请求参数

java - 转换为 UTC 日期后生成时间戳

java - Grails 线程

java - 如何在 JavaFX 中从数据库创建自定义 LookUp 搜索小部件

java - Java 中的条件 SQL where 子句