首页 文章

从java程序在groovy脚本中填充变量

提问于
浏览
1

我知道如何从Java代码中调用Groovy代码,但是,在运行Groovy脚本 script.groovy 时,您是否可以请求Java程序填充其varabies?

// script.groovy
import static org.mydomain.WiseJavaProgram.*;
pleasePopulateMeWithVariables();
println numberOfLegs // 2
// We didn't declare numberOfLegs in our sript, the Java program set it for us.

我想也许因为 script.groovy 应该将其环境传递给 pleasePopulateMeWithVariables 方法,但我还没有找到如何做到这一点 . 这甚至可能吗?

我想要使用这种行为的情况:我有 script.groovy ,还有一个未定义的groovy脚本,Java程序知道这些脚本,但 script.groovy 不知道,我想将它们中声明的内容添加到 script.groovy . 基本上,这些附加脚本是数据,例如各种产品及其功能的描述 . 如果您运行创建GroovyShell并在其中计算数据脚本然后 script.groovy 的Java程序,这很容易,但对我来说,我们最初需要调用 script.groovy ,而不是Java程序 .

1 回答

  • 1

    和往常一样,在问这个问题的时候,我是一步一步回答--__-

    我正在搜索的"environment"是 Script 对象本身,可以从 script.groovy 获得,只需 this . 所以:

    // script.groovy
    import static org.mydomain.WiseJavaProgram.*;
    populateWithVariables(this);
    println numberOfLegs // 2
    
    // WiseJavaProgram.java
    public class WiseJavaProgram {
      public static void populateWithVariables(Script script) {
        script.evaluate('numberOfLegs = 2');
        script.evaluate(new File("another.groovy"));
        script.evaluate(new File("yetAnother.groovy"));
      }
    }
    

相关问题