如何为内部Groovy DSL创建没有参数和大括号的单字命令

时间:2017-09-25 11:00:20

标签: java groovy dsl

我试图创建一个groovy内部dsl,后来用于记录和重放几个java命令的执行。实施在底层。

我真的想实现一个单词命令。

示例:

exit

编辑:如果我使用exit()调用该命令,则可以正常工作。有没有办法摆脱大括号?

到目前为止,我已经能够使用一个或多个参数执行命令。例如:

jump ON, "Table"

execute "commandlist.myowndsl"

当我按如下方式绑定exit时,它当然会在设置shell时评估Binding,而不是在发出命令时。

class MyBindings {
    static Binding getMyBindings() {
        return new Binding([
                exit:   MyCommandLine.exit,
        ])
    }
}

但是,如果我将其绑定到:

exit: MyCommandLine.&exit

它只会创建一个闭包,我必须使用exit.call()来调用,这不是我想要的。

是否有可能通过绑定或其他方式摆脱大括号?

代码:

设置GroovyShell:

CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass("shellDefinitions.MyCommandLine");
ImportCustomizer importCustomizer = new ImportCustomizer();
importCustomizer.addStaticStars("shellDefinitions.Prepositions");       
config.addCompilationCustomizers(importCustomizer);
GroovyShell shell = new GroovyShell(Main.class.getClassLoader(), MyBindings.getMyBindings(), config);

现在我输入如下命令:

Scanner reader = new Scanner(System.in);
String inLine;
do {
    System.out.print("> ");
    inLine = reader.nextLine();
    shell.evaluate(inLine);
} while (!inLine.equals("exit"));

MyCommandLine:

class MyCommandLine extends Script {

    static def jump(Prepositions prep, String where) {
        JumpCommand cmd = new JumpCommand(System.out)
        cmd.setTarget(prep, where)
        cmd.execute()
        return this
    }

    static def exit() {
        System.out.println("Exiting...")
        return this
    }

    @Override
    Object run() {
        return this
    }
}

0 个答案:

没有答案