我正在使用 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