如何在没有前缀的情况下从嵌入式groovy调用Java方法和访问属性

时间:2013-07-30 12:36:24

标签: java groovy

我使用GroovyScriptEngine将Groovy嵌入到Java应用程序中。我将所有相关属性放入绑定中,一切正常。为了完整起见,这是一个片段:

public class GE2 {
    GroovyScriptEngine gse;
    Binding binding;

    public GE2() throws Exception {
        this.gse = new GroovyScriptEngine(new String[]{"scripts"});
        binding = new Binding() {

            @Override
            public Object getProperty(String property) {
                // this method is never called when trying println name2 from groovy
                return "Prop: " + property;
            }

        };
        binding.setVariable("GE2", this);
        gse.run("t1.groovy", binding);
    }

    public String getName() {
        return "theName";
    }

    public void doIt(String... args) {
        System.out.printf("Doing it with %s\n", Arrays.toString(args));
    }

    public static void main(String[] args) throws Exception {
        new GE2();
    }
}

我的groovy脚本t1.groovy如下:

println GE2.name // this correctly prints theName
// println name2 <- this raises No such property: name2 for class: t1
GE2.doIt('a', 1, 42); // this works as expected too

有没有办法可以“绕过”GE2.并直接从脚本中使用GE2 属性和方法

我正在使用JDK 7和Groovy 2.1

2 个答案:

答案 0 :(得分:2)

CompilerConfiguration可让您设置scriptBaseClass,从中调用内容。你能用GroovyShell吗?似乎有some caveats GroovyScriptEngineCompilerConfiguration(尽管它们可能已解决/可解决):

档案Shell.groovy

def script = '''
  println GE3.name // this now prints the GE3's class name
  println name 
  doIt 'a', '1', '42'
'''


def config = new org.codehaus.groovy.control.CompilerConfiguration(scriptBaseClass: GE3.class.name)
def binding = new Binding()


new GroovyShell(binding, config).evaluate script

档案GE3.groovy

abstract class GE3 extends Script {
  String getName() { "John Doe" }

  void doIt(String... args) {
    System.out.printf("Doing it with %s\n", Arrays.toString(args));
  }
}

答案 1 :(得分:0)

您可以自己实施所有成员并将其链接

public void doIt(String... args) {
    GE2.doIt(args);
}

因此从你自己的班级打电话给他们。