java groovy mix中的委托对象方法内的访问绑定

时间:2017-08-15 12:11:58

标签: java groovy

我有以下" java"类:

public class GScript {
    public static void main(String[] args) throws Exception {
        Binding binding = new Binding();
        binding.setVariable("a", "a");

        CompilerConfiguration cc = new CompilerConfiguration();
        cc.setScriptBaseClass(DelegatingScript.class.getName());
        GroovyShell sh = new GroovyShell(ClassLoader.getSystemClassLoader(), binding, cc);
        DelegatingScript script = (DelegatingScript) sh.parse(GScript.class.getResource("/org/devocative/samples/groovy/my.dsl.txt").toURI());
        script.setDelegate(new MyDSL());
        script.run();
    }

    public static class MyDSL {
        public Object exec(String commandName, Map<String, Object> params) {
            // String a = (String)binding.getVariable("a"); HOW???
            return String.format("cmd = %s, params = %s", commandName, params);
        }

        public Object ssh(String prompt, String cmd, boolean force, String... stdin) {
            return String.format("prompt = %s, cmd = %s, force = %s, stdin = %s", prompt, cmd, force, Arrays.toString(stdin));
        }
    }
}

这是我的DSL:

e = exec "withParam", [a:'a', b:1]

println "e = $e"

e = ssh "prompt", "exec oops!", true

println "e = $e"

e = ssh "prompt", "exec oops!", true, '1', '2', '3'

println "e = $e"

我想在MyDSL的方法中访问绑定对象(例如获取&#34; a&#34;值)。问题是MyDSL类是用java编写的。如何访问绑定对象,如上面评论的代码?

PS:我想在MyDSL类中访问绑定,因为我把脚本对象放在缓存中,所以只有一个脚本对象,所以MyDSL类只有一个实例,但基于绑定变量值,执行为每种方法都必须不同。

0 个答案:

没有答案